As far as I know, go is statically typed and usually does not perform implicit type conversion. Therefore, constants without an explicit type declaration are subject to requirements on first use.
So, in the code snippet below, I wantn
to befloat64
, because that's whatmath.sin
expects. But when printing out the reflected type, I seeint
.
package main import ( "fmt" "math" "reflect" ) func main() { const n = 5000 // No explict type // fmt.Println(reflect.TypeOf(n)) // this would print "int" fmt.Println(math.Sin(n)) // math.Sin expects a float64 fmt.Println(reflect.TypeOf(n)) // print "int" }
What exactly happened here?n
Is there actually an implicit int type? Or reflection won't show actual type cases like this? I don't thinkmath.sin
is typecasting its argument because the compiler will throw an error if I specify an explicit type.
[The type of untyped constant] depends on the requirements for first use.
This is where you got it wrong. A type is selected independently for each use.
math.Sin requires a float64 argument, so the compiler must select float64 here.
reflect.TypeOf takes an interface{} parameter, so the compiler is free to choose any numeric type (since they all implement the empty interface). The default integer type is selected here: int.
The above is the detailed content of How does type reflection for implicit types work?. For more information, please follow other related articles on the PHP Chinese website!