go中的type

栏目: Go · 发布时间: 6年前

  1. type分三类

    1. 预声明标识类型,基本就是boolean,numeric and string
    2. 复合类型,如:map slice arry struct interface pointer function channel 这些使用(type字面量)构造的类型
    3. 自声明类型,分两种:

      var Age int // 类型定义
      var Int = int // 类型别名
      • 类型定义,type: 一人千面

        • 创建了一个完全新的类型,与其所基于的类型是两个不同的类型。
        • 不继承底层类型的方法,但会继承底层类型的元素(如果是interface类型,那么其方法集也会保留下来,在我看interface的方法集实际上类似于字段)
      • 类型别名,类型别名是给某个类型起的别名,该别名本质上依然是该类型。
  2. 底层类型,每一个type都有其底层类型,1和2类的底层类型都是其本身,3的底层类型视情况而定。

    type (
        A1 = string
        A2 = A1
    )
    
    type (
        B1 string
        B2 B1
        B3 []B1
        B4 B3
    )

    A1,A2,B1,B2的底层类型都是string,B3,B4的底层类型都是[]B1

  3. 接口类型(interface type),推荐看 Go接口深入解析

    interface {}
    
    type ReadWriter interface {
        Read(b Buffer) int
        Write(b Buffer) int
    }
    type File interface {
        ReadWriter
        Close()
    }
  4. 结构体类型,结构体是命名元素的序列,我们称这些命名元素为字段,每个字段都有名字(name)和类型(type)。非空字段的名字必须唯一,字段可以显式或者隐式(一个字段只有type而没有名字)的指定。

    • 隐式字段称为嵌入字段。嵌入字段要么是个类型,要么是个非接口类型的指针类型。
    typt T struct {
        name string
    }
    
    type T1 struct {
        value int // 正常字段
        int // 嵌入字段:int类型
        *T  // 嵌入字段:指向类型T的指针类型
    }
    • 如果一个 type T1 被嵌入另一个 type T 作为它的 filed,T1 的所有 field 和 method 都可以在 T 中使用
    • 空结构体 ,重要的是其内存消耗等于0。

参考

  1. Go类型系统
  2. Go官方文档

以上所述就是小编给大家介绍的《go中的type》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pattern Recognition and Machine Learning

Pattern Recognition and Machine Learning

Christopher Bishop / Springer / 2007-10-1 / USD 94.95

The dramatic growth in practical applications for machine learning over the last ten years has been accompanied by many important developments in the underlying algorithms and techniques. For example,......一起来看看 《Pattern Recognition and Machine Learning》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

MD5 加密
MD5 加密

MD5 加密工具