# 6.golang函数、指针、结构体

## 函数

### 函数声明

``````func name(parameter) (result-list){
//body
}
``````

``````func name() {
//body
}
``````

### 单返回值函数

``````func plus(a, b int) (res int) {
c := a + b
return c
}

func main() {
a, b := 90, 6
sumAll := plus(a, b)
fmt.Println("sum", sumAll)
}
``````

### 多返回值函数

``````func plus(a, b int) (int, int) {
c := a + b
d := a - b
return c, d
}

func main() {
a, b := 90, 6
sumAll, subAll := plus(a, b)
fmt.Println("sum", sumAll)
fmt.Println("sub", subAll)
}
``````

``````sum 96
sub 84
``````

### 命名返回值

``````func plus(a, b int) (res int) {
res = a + b
return
}

func main() {
a, b := 90, 6
sumAll := plus(a, b)
fmt.Println("sum", sumAll)
}
``````

### 参数可变函数

``````func sum(nums ...int) (res int) {
fmt.Println("len of nums is : ", len(nums))
res = 0
for _, v := range nums {
res += v
}
return
}

func main() {
fmt.Println(sum(1))
fmt.Println(sum(1, 2))
fmt.Println(sum(1, 2, 3))
}
``````

``````len of nums is :  1
1
len of nums is :  2
3
len of nums is :  3
6
``````

### 匿名函数

``````func main() {
func(name string) {
fmt.Println(name)
}("初辰ge")
}
``````

## 指针

### 指针的声明

``````func main() {
a := 255
b := &a
fmt.Println(b)
fmt.Println(*b)
}
``````

& 操作符获取一个变量的指针地址。* 操作符获取指针地址的值。程序的输出为：

``````0xc00000a0d8
255
``````

## 结构体

### 声明结构体

``````type StructName struct{
FieldName type
}
``````

### 声明结构体并赋值

``````type Student struct {
age  int
name string
}

func main() {
stu := Student{
age:  18,
name: "初辰ge",
}
fmt.Println(stu)
}
``````

``````{18 初辰ge}
``````

### 获取结构的各个字段

`.`运算符用于访问结构的各个字段。

``````type Student struct {
age  int
name string
}

func main() {
stu := Student{
age:  18,
name: "初辰ge",
}
fmt.Println(stu.name)
}
``````

``````初辰ge
``````

### 嵌套结构体

``````type Student struct {
age  int
name string
dog  Dog
}
type Dog struct {
age  int
name string
}

func main() {
stu := Student{
age:  18,
name: "初辰ge",
dog: Dog{
age:  2,
name: "小白",
},
}
fmt.Println(stu.dog.name)
}
``````

``````小白
``````

THE END

)">