golang-结构体

5次阅读

共计 653 个字符,预计需要花费 2 分钟才能阅读完成。

普通结构体

1.public

type Flower struct {
    Name string
    Color string
    Category string
}

外部包可以直接引用和赋值
2.private

type leaf struct {
    count int
    size int
}

外部包不能直接引用
需要定义 public 函数提供操作,例如

func (l *leaf) SetColor(color string) {l.color = color}

3.public 结构体里面有 private

type Flower struct {
    Name string
    Color string
    Category string
}

这种情况下,只能通过 public 的函数或者方法来操作内部的 private 属性
4.private 结构体里面有 public 属性

type leaf struct {
    color string
    size int
    Count int
}

这种也是允许的,例如:

func NewLeaf(color string, size, count int) *leaf{var l = leaf{color, size, count}
    return &l
}

在另一个包中引用这些结构体

func main() {leaf := plant.NewLeaf("green", 5, 10)
    fmt.Println(leaf)
    leaf.Count = 5
    fmt.Println(leaf)
}

输出:

&{green 5 10}
&{green 5 5}

很少看到这么使用

json/xml 结构体

待补充。。。

嵌套结构体

待补充。。。

嵌套匿名结构体

待补充。。。

结构体中嵌套接口

待补充。。。

正文完
 0