The Go Programming Language Specification says that:
Constants may be typed or untyped
I am having a little doubt in my understanding. Consider this example in the spec:
const l = "hi" // l == "hi" (untyped string constant)
const m = string(k) // m == "x" (type string)
The spec says:
constant may be given a type explicitly by a constant declaration or conversion, or implicitly when used in a variable declaration or an assignment or as an operand in an expression
By this statement, why isn't l
typed since it is clearly a constant declaration?
This behaviour is clearer with another example
type Foo string
func f(a Foo) {}
func main() {
f("sarkozy")
const t = "julie gayet"
f(t)
s := "hollande"
//compile error
// f(s)
f(Foo(s)) // ok
}
Is the reason that f("sarkozy")
compiles be due to this statement on Assignability in the spec?
x is an untyped constant representable by a value of type T.
My argument is the following:
- "sarkozy" a an untyped literal.
- Thus "sarkozy" being representable by
Foo
means I can type coerce like thisFoo("sarkozy")
-
f(s)
fails because s is not untyped.