How does type reflection for implicit types work?

王林
Release: 2024-02-06 09:30:08
forward
877 people have browsed it

How does type reflection for implicit types work?

Question content

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 wantnto befloat64, because that's whatmath.sinexpects. 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" }
Copy after login

What exactly happened here?nIs there actually an implicit int type? Or reflection won't show actual type cases like this? I don't thinkmath.sinis typecasting its argument because the compiler will throw an error if I specify an explicit type.


Correct answer


[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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!