隐式类型的类型反射是如何工作的?

huangapple go评论86阅读模式
英文:

How does type reflection for implicit types work?

问题

根据我理解,Go是静态类型的,并且通常不进行隐式类型转换。因此,没有显式类型声明的常量在首次使用时会根据需要进行推断。

因此,在下面的代码片段中,我期望n是一个float64,因为这是math.Sin所期望的类型。但是当打印出反射类型时,我看到的是一个int

package main

import (
	"fmt"
	"math"
	"reflect"
)

func main() {
	const n = 5000 // 没有显式类型声明

        // fmt.Println(reflect.TypeOf(n)) // 这将打印出 "int"

	fmt.Println(math.Sin(n)) // math.Sin 期望一个 float64

	fmt.Println(reflect.TypeOf(n)) // 打印出 "int"
}

这里实际上发生了什么?n实际上具有隐式的int类型吗?还是反射在这种情况下不显示实际类型?我认为math.Sin没有对其参数进行类型转换,因为如果我指定显式类型,编译器会报错。

英文:

From what I've understood, Go is statically typed and doesn't normally do implicit type conversions. So constants declared without an explicit type get based on what's required when they are first used.

So in the following snippet, I'd expect n to be a float64, since that's what math.Sin expects. But when printing out the reflected type, I see an 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's actually happening here? Does n actually have an implict int type? Or does reflection not show the actual type cases like this? I don't think math.Sin is typecasting it's argument since the compiler throws an error if I specify an explicit type.

答案1

得分: 3

根据首次使用时所需的内容,"未类型化的常量会被赋予类型"。

这是你误解的地方。每次使用都会独立选择一种类型。

math.Sin需要一个float64参数,所以编译器在这里必须选择float64。

reflect.TypeOf接受一个interface{}参数,所以编译器可以自由选择任何数值类型(因为它们都实现了空接口)。在这里,它选择了默认的整数类型:int。

英文:

> [Untyped constants get typed] based on what's required when they are first used.

This is where you're misunderstanding. A type is selected for every use independently.

math.Sin requires a float64 argument, so the compiler must select float64 here.

reflect.TypeOf takes an interface{} argument, so the compiler is free to choose any of the numeric types (because they all implement the empty interface). Here it chose the default integer type: int.

huangapple
  • 本文由 发表于 2023年2月15日 19:04:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75458849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定