【问题标题】:How can the "static type" and "dynamic type" be different?“静态类型”和“动态类型”怎么会不同呢?
【发布时间】:2017-09-08 00:12:38
【问题描述】:

根据 Nim 手册,变量类型是“静态类型”,而变量在内存中指向的实际值是“动态类型”。

它们怎么可能是不同的类型?我认为将错误的类型分配给变量会是一个错误。

【问题讨论】:

    标签: types nim-lang


    【解决方案1】:
    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
    

    【讨论】:

      猜你喜欢
      • 2012-07-11
      • 2010-12-02
      • 1970-01-01
      • 2016-12-15
      • 2016-09-26
      • 2012-06-29
      • 1970-01-01
      相关资源
      最近更新 更多