mercredi 30 mars 2016

How do programs know the types at runtimes of primitives statically typed languages

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?





Aucun commentaire:

Enregistrer un commentaire