04-方法-02-结构体和方法
1. 方法
1.1 代码结构
1.2 struct_demo.go
package struct_demo
import "fmt"
//定义机构体
type Xishu struct {
ID int
Name string
Age int
Position string
}
//定义方法
func (xishu *Xishu)Run() {
fmt.Println("姓名: ",xishu.Name)
fmt.Println("职务: ",xishu.Position)
}
1.3 main.go
package main
import "814/struct_demo"
func main () {
//定义数据
liubei := new(struct_demo.Xishu)
liubei.ID = 0
liubei.Name = "刘备"
liubei.Age = 28
liubei.Position = "主公"
//调用方法
liubei.Run()
}
1.4 结果
2. 组合
结构体组合使用
2.1 代码结构
2.2 struct_demo.go
package struct_demo
import "fmt"
//再定义一个Power结构体
type Power struct {
Atk int
Def int
}
type Xishu struct {
ID int
Name string
Age int
Position string
//Xishu中引用Power这个结构体
Power
}
func (xishu *Xishu)Run() {
fmt.Println("姓名: ",xishu.Name)
fmt.Println("职务: ",xishu.Position)
//为了验证结果,在方法中加入Power的内容
fmt.Println("攻击力: ",xishu.Atk)
fmt.Println("防御力: ",xishu.Def)
}
2.3 main.go
package main
import "814/struct_demo"
func main () {
liubei := new(struct_demo.Xishu)
liubei.ID = 0
liubei.Name = "刘备"
liubei.Age = 28
liubei.Position = "主公"
//Xishu中拥有的Power的属性
liubei.Atk = 200
liubei.Def = 300
liubei.Run()
}