Home  >  Article  >  Backend Development  >  How does type reflection for implicit types work?

How does type reflection for implicit types work?

王林
王林forward
2024-02-06 09:30:08903browse

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 want n to be float64, because that's what math.sin expects. But when printing out the reflected type, I see int.

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 think math.sin is 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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete