go 结构体

前端之家收集整理的这篇文章主要介绍了go 结构体前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

go 结构体

Go 通过结构体的形式支持用户自定义类型。

结构体是复合类型(composite types),当需要定义一个类型,它由一系列属性组成,每个属性都有自己的类型和值的时候,就应该使用结构体,它把数据聚集在一起。然后可以访问这些数据,就好像它是一个独立实体的一部分。

定义

结构体定义的一般方式如下:

  1. type Identifier struct {
  2. field1 type1
  3. field2 type2
  4. ...
  5. }

赋值

结构体是值类型,因此可以通过 new 来创建。

我们可以使用 . 给字段赋值:

  1. structname.fieldname = value

同样的,也可以使用 . 获取结构体字段的值:

  1. structname.fieldname

在 Go 语言中这叫 selector。无论变量是一个 结构体类型 还是一个 结构体类型指针,都使用同样的 selector-notation 来引用结构体的字段:

  1. type myStruct struct { i int }
  2. var v myStruct // v 是结构体类型变量
  3. var p *myStruct // p 是指向一个结构体类型变量的指针
  4. v.i
  5. p.i

下面来看一个例子

  1. // rectangle.go
  2. package rect
  3.  
  4. type Rectangle struct {
  5. length int
  6. width int
  7. }
  8.  
  9. func (r *Rectangle) Set(x,y int) {
  10. r.length = x
  11. r.width = y
  12. }
  13.  
  14. func (r *Rectangle) Area() (res int) {
  15. res = r.length * r.width
  16. return
  17. }
  18.  
  19. func (r *Rectangle) Perimeter() (res int) {
  20. res = (r.length + r.width) * 2
  21. return
  22. }
  1. // main.go
  2. package main
  3.  
  4. import (
  5. "rect"
  6. "fmt"
  7. )
  8.  
  9. func main() {
  10. rectangle := new(rect.Rectangle)
  11. rectangle.Set(1, 2)
  12. fmt.Println("rectangle is",rectangle)
  13. fmt.Println(rectangle.Area())
  14. fmt.Println(rectangle.Perimeter())
  15. }

运行结果

  1. rectangle is &{1 2}
  2. 2
  3. 6

注意:如果 XX 是一个结构体类型,那么表达式 new(XX)&XX{} 是等价的。

例如:

  1. type MyStruct struct {
  2. x int
  3. y int
  4. }
  5.  
  6. my := new(MyStruct)
  7. my.x = 1
  8. my.y = 2
  9.  
  10. 等价于
  11.  
  12. my2 := &Mystrcut{1, 2}

工厂方法

你现在突然想,不能让别人看到我的结构体,我应该把它设为私有的,但是还想让别人使用我的结构体,该怎么办?

为了方便,通常会为类型定义一个工厂,按惯例,工厂的名字以 new 或 New 开头,它返回一个指向结构体实例的指针。形式如下:

  1. // mystruct.go
  2. package my
  3.  
  4. type mystruct struct {
  5. ...
  6. }
  7.  
  8. func NewMystruct() *mystruct {
  9. m : = new(mystruct) // 初始化 m
  10. return m
  11. }

在其他包里使用工厂方法

  1. // main.go
  2. package main
  3.  
  4. import "my"
  5. ...
  6.  
  7. wrong : = new(my.mystruct) // 编译失败,mystruct 是私有的
  8. right : = my.NewMystruct() // 实例化 mystruct 的唯一方式

猜你在找的Go相关文章