【发布时间】:2016-07-18 14:05:17
【问题描述】:
Go 和 Scala 都提供了在运行时检查类型的方法:
斯卡拉:
class A
class B extends A
val a: A = new A // static type: A dynamic type: A
val ab: A = new B // static type: A dynamic type: B
val b: B = new B // static type: B dynamic type: B
def thing(x: Any): String = x match {
case t: Int => "Int"
case t: A => "A"
case t: B => "B"
case t: String => "String"
case _ => "unknown type"
}
去:
package main
import (
"fmt"
"reflect"
)
struct A {
field1 int
field2 string
}
func printTypeOf(t interface{}) {
fmt.Println(reflect.TypeOf(t))
}
func main() {
i := 234234 // int
s := "hello world" // string
p := &A{3234234, "stuff"} // *A
fmt.Print("The type of i is: ")
printTypeOf(i)
fmt.Print("The type of s is: ")
printTypeOf(s)
fmt.Print("The type of p is: ") // pass a pointer
printTypeOf(p)
fmt.Print("The type of the reference of p is: ") // pass a value
printTypeOf(*p)
}
这在内部究竟是如何工作的?我假设对于结构和类,对象的类型存储在一个隐藏字段中(所以 golang 中的结构实际上是 struct { field1 int field2 string type type }。但是到底如何才能发挥作用,给出 11010110 并知道它是否是指向内存地址 214 的指针,整数 214 还是字符 Ö?是否所有的值都偷偷地用一个代表其类型的字节传递?
【问题讨论】:
-
您的假设不正确,Go 结构中没有隐藏字段。所有类型在编译时对编译器都是已知的。
-
Go,简单来说:当你调用
printTypeOf(x)时,x 被包装在一个接口值中。该值具有您所考虑的“隐藏字段”。 -
鉴于它是包装好的,这是有道理的
标签: scala reflection go types