从零开始学Go之基本(五):结构体

结构体:

声明:

type 结构体名 struct{
​
 结构体内部字段
​
}

例子:

type UserInfo struct {
 Id    string `json:"id"`
 Name   string `json:"name"`
 Headpicture string `json:"headpicture"`
 Info   string `json:"info"`
}

实例化:

package main
​
import "fmt"
​
type Vertex struct {
 X, Y int
}
​
var v Vertex // 创建一个 Vertex 类型的结构体
var (
 v1 = Vertex{1, 2} // 创建一个 Vertex 类型的结构体并显式赋值
 v2 = Vertex{X: 1} // Y:0 被隐式地赋予,即默认值
 v3 = Vertex{}  // X:0 Y:0
 p = &Vertex{1, 2} // 创建一个 *Vertex 类型的结构体(指针)
)
​
func main() {
 v.X = 3
 v.Y = 3
 fmt.Println(v, v1, v2, v3, p)
}

运行结果

{3 3} {1 2} {1 0} {0 0} &{1 2}

new关键字:

可以使用 new 关键字对类型(包括结构体、整型、浮点数、字符串等)进行实例化,结构体在实例化后会形成指针类型的结构体

type Vertex struct {
 X, Y int
}
​
func main() {
 i := new(int)//创建一个int指针
 v := new(Vertex)//相当于v = &Vertex{},创建一个Vertex结构体指针
 v.X = 3
 fmt.Println(i, v, &v)
}

运行结果

0xc04204e080 &{3 0} 0xc04206c018

取地址实例化:

由于 变量名 = &结构体名{} 的方式是实例化一个结构体指针,这时候可以通过指针的方式来对结构体实例化的同时进行赋值。

type Vertex struct {
 X, Y int
}
​
func NewVertex(X,Y int)*Vertex {//封装实例化过程
 return &Vertex{
  X: X,
  Y: Y,
 }
}
​
func main() {
 v1 := new(Vertex)
 v2 := &Vertex{}
 v := &Vertex{
  X:3,//可以利用键值对来只对一个值进行赋值
 }
 v1 = v
 v2 = NewVertex(8,9)
 fmt.Println(v1, v2)
}

运行结果

&{3 0} &{8 9}

构造函数:

在C中的构造函数是与原结构体同名,但参数不同的重载函数完成,但Go中只能通过模拟这一特性完成构造函数,即通过多个不重名函数通过取地址实例化完成。

type Vertex struct {
 X, Y int
}
​
func NewVertexX(X int)*Vertex {
 return &Vertex{
  X: X,
 }
}
​
func NewVertexY(Y int)*Vertex {
 return &Vertex{
  Y: Y,
 }
}
​
func NewVertex(X,Y int)*Vertex {
 return &Vertex{
  X: X,
  Y: Y,
 }
}
原文地址:https://www.cnblogs.com/VingB2by/p/11073853.html