Go进阶(一)

Golang 学习

结构体

在 Go 语言中,允许用户自己定义数据类型。常用struct关键字来创建一个结构类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// user为自定义的数据类型
type user struct {
name string
age int
sex string
address string
}

// 声明变量
// 方法一
var thomas user
thomas.name, thomas.age, thomas.sex, thomas.address := "Thomas", 20, "male", "America"

// 方法二
thomas := user{
name: "Thomas",
age: 20,
sex: "male",
address: "America",
}

// 方法三
// 顺序必须和结构体声明的顺序一致
thomas := user{"Thomas", 20, "male", "America"}

方法

方法可以给用户定义的类型添加新的行为。方法本质也是函数,区别就是在声明的时候,在关键字 func 和方法名称之间加上了一个接受者。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import "fmt"

// define a struct type
type user struct {
name string
address string
}

// getBasicInfo使用值接受者实现了一个方法
// 值接受者会使用这个值的副本
func (u user) getBasicInfo() (name, address string) {
fmt.Printf("%s's address is %s\n", u.name, u.address)
return u.name, u.address // 即使函数使用了命名返回值,你依旧可以无视它而返回明确的值
}

// setBasicInfo使用指针接受者实现了一个方法
// 值接受者会使用这个值的指针,会修改外部变量
func (u *user) setBasicInfo(address string) {
u.address = address
fmt.Printf("%s's address is be set as %s\n", u.name, u.address)
}

func main() {
laxx := user{"Laxx", "Anywhere You Wanna"}
laxx.getBasicInfo()
laxx.setBasicInfo("where i set")
}

/*
上面的内容的输出:
Laxx's address is Anywhere You Wanna
Laxx's address is be set as where i set
*/

©Written By flyaooo