Golang is extremely explicit with types. It supports constants of a type. But how about a const 2
or hello
. What type would they assume!?
Go solved this problem with untyped constants. Untyped means:
- A constant’s type depends on the type of assignee variable.
- The assignee’s type must have compatibility to hold constant’s value.
Example
package main
import (
"fmt"
)
const (
myconst = `a untyped constant`
anotherConst = "a typed const"
)
type myStrType string
func main() {
fmt.Println("vim-go")
var name string
var number int
// Since name is of type string, both untype & typed string
// constants work fine.
name = myconst
name = anotherConst
// Doesn't work because a untyped string still is a string.
// We can't assign it to an integer.
// number = myconst
fmt.Println(name, number)
// This is the use case of untyped consts.
// A compatible type can hold an untyped constant.
var newStr myStrType // <---------
newStr = myconst
fmt.Println(newStr)
}
Output
$ go run untyped_consts.go vim-go
a typed const 0
a untyped constant
Remember
- An untyped constant still has the type.
- Only a
typedef
of original type can hold a untyped constant.