类型系统

Go 类型系统 #

Underlying Type #

  • 每一个类型都有自己的 Underlying Type
    • 如果 TPre-declared type 或者 Type Literal,它们对应的 Underlying Type 就是自身 T
      • 比如 type T intUnderlying Typeint
        • intPre-declared
      • type T map[int]stringUnderlying Typemap[int]string
        • map[int]stringType Literal
    • 否则 TUnderlying TypeT 定义时引用的类型的 Underlying Type

Underlying Type 相同 #

如果两个 type 的 Underlying Type 相同,则它们可以有以下特性:

  • 如果两个 type 都是 named type ,彼此之间不能相互赋值

    type NewString string
    var my string ="a"
    // cannot use my (type string) as type NewString in assignment
    // 虽然它们的 Underlying Type 都是 string,但 string 类型的 my 不能赋值给 NewString 类型的 you
    var you NewString = my
    
  • 如果两个 type 其中一个是 Unnamed Type,彼此之间可以相互赋值

    package main
    
    type Ptr *int
    //named type
    type Map map[int]string
    type MapMap Map
    
    func main() {
        var p *int
        var mm Map
        var mmm MapMap
        // m1 m2 是 Unnamed Type
        var m1 map[int]string = mm
        var m2 map[int]string = mmm
        var ptr Ptr = p
        print(ptr)
        print(m1)
        print(m2)
    }
    

原因: 如果为一个类型起了名字,说明你想要做区分,所以两个 named types 即使 Underlying Type 相同也是不能相互赋值的。

参考:


本文访问量

本站总访问量

本站总访客数