美文网首页
golang:struct

golang:struct

作者: 程序员饭饭 | 来源:发表于2018-01-04 13:48 被阅读0次
在golang中,struct类型能够将其他数据类型组合或内嵌在一起,struct是复合类型。
struct不同初始化方式
// Point结构体类型定义
type Point struct {
    x, y int
}

// 结构体类型的声明及初始化
var p Point    //使用var声明一个Point对象,分配内存
var p *Point  //使用var声明一个Point类型的指针,Point对象未分配内存
p := new(Point) //使用new关键字返回一个指向Point对象的指针,分配内存
p := Point{}    //使用字面量初始化
p := Point{x: 10, y: 20} //使用字面量初始化
struct中的内嵌类型

在struct类型中,字段名必须是唯一的,也就是说如果有嵌入的类型,则嵌入类型的字段名也必须是唯一的

// A struct with four embedded fields of types T1, *T2, P.T3 and *P.T4
struct {
    T1        // field name is T1
    *T2       // field name is T2
    P.T3      // field name is T3
    *P.T4     // field name is T4
    x, y int  // field names are x and y
}

// 下面的声明的struct是不合法的
struct {
    T     // conflicts with embedded field *T and *P.T
    *T    // conflicts with embedded field T and *P.T
    *P.T  // conflicts with embedded field T and *T
}

相关文章

网友评论

      本文标题:golang:struct

      本文链接:https://www.haomeiwen.com/subject/djlrnxtx.html