dongzhashou0116 2016-03-30 13:57
浏览 52
已采纳

程序如何在基元静态类型化语言的运行时知道类型

Both Go and Scala provide ways of checking types at runtime:

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"
}

Go:

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)
}

How exactly does this work internally? I presume for structs and classes, the type of the object is stored in a hidden field (so the structure in golang is really struct { field1 int field2 string type type }. But how on earth can function be given 11010110 and know whether it's a pointer to memory address at 214, the integer 214 or the character Ö? Are all values secretly passed with a byte which represents its type?

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法