go - What does it mean for a constant to be untyped in golang? -
the spec says that:
constants may typed or untyped
i having little doubt in understanding. consider example in spec:
const l = "hi" // l == "hi" (untyped string constant) const m = string(k) // m == "x" (type string) the spec says:
constant may given type explicitly constant declaration or conversion, or implicitly when used in variable declaration or assignment or operand in expression
by statement, why isn't l typed since constant declaration?
this behaviour clearer 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 reason f("sarkozy") compiles due statement on assignability in spec ?
x untyped constant representable value of type t.
my argument following:
- "sarkozy" untyped literal.
- thus "sarkozy" being representable
foomeans can type coercefoo("sarkozy") f(s)fails because s not untyped.
why isn't l typed since constant declaration?
yes, constant declaration, quote says:
constant may given type explicitly constant declaration
however, in case there no explicitly given type. can have implicitly given type when "used in variable declaration or assignment or operand in expression".
is reason f("sarkozy") compiles due statement on assignability in spec ?
yes, reason f("sarkozy") compiles because untyped constant of "sarkozy" has type given implicitly when used operand in expression such in case.
"sarkozy" implicitly given type of foo
so why doesn't f(s) compile? (okay, not in question, question remains)
your argument states that: "f(s) fails because s not untyped."
true s not untyped. s variable , not constant, , variables cannot untyped.
the go specs states variable declarations:
if type absent , corresponding expression evaluates untyped constant, type of declared variable described in §assignments.
and refers, understand following:
the constant first converted type bool, rune, int, float64, complex128 or string respectively, depending on whether value boolean, rune, integer, floating-point, complex, or string constant.
so, following line:
s := "hollande" will declare variable (not constant) s of type string because right-hand expression untyped string constant. type implicitly given during declaration of variable, not analyzing context later on used.
f(s) result in compile error because try use value of type string value of type foo expected.
Comments
Post a Comment