“静态类型”和“动态类型”有何不同?

4
根据Nim手册,变量类型是“静态类型”,而在内存中变量指向的实际值是“动态类型”。
它们为什么可以是不同的类型呢?我以为将错误的类型分配给变量会导致错误。
1个回答

8
import typetraits

type
  Person = ref object of RootObj
    name*: string
    age: int

  Student = ref object of Person # a student is a person
    id: int

method sayHi(p: Person) {.base.} =
  echo "I'm a person"

method sayHi(s: Student) =
  echo "I'm a student"

var student = Student(name: "Peter", age: 30, id: 10)
var person: Person = student # valid assignment to base type
echo person.repr # contains id as well
echo name(person.type) # static type = Person
person.sayHi() # dynamic type = I'm a student

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接