行くと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の構造体は実際に構造体{field1 int field2 string type type}です)しかし、どのように機能するかは11010110で与えられ、メモリアドレスへのポインタ214、整数214または文字Öすべての値は、その型を表すバイトで密かに渡されますか?
あなたの推測は間違っていますが、Go構造体には隠しフィールドはありません。すべての型はコンパイル時にコンパイラに知られています。 – JimB
単純に言えば、 'printTypeOf(x)'を呼び出すと、xはインターフェース値にラップされます。この値には、あなたが考えていた「隠しフィールド」があります。 – thwd
それはラップされているので、それは意味があります – user2850249