package main
import ( "fmt" _ "fmt" )
func main() { //声明一个猫的结构体,是一种数据类型 type Cat struct { Name string //结构体的组成部分 Color string //字段的声明类似变量的声明,不赋值默认为0,nil Age int Hobor string } type Person struct { Name string Age int prt *int //指针 Adress []string //切片 Score map[string]int //map类型 } //cat是个Cat的结构体 var cat Cat cat.Name = "猫咪" cat.Age = 3 cat.Color = "白色" cat.Hobor = "fish" fmt.Println("cat=", cat) fmt.Println("cat的名字是", cat.Name) fmt.Println("名字的地址", &cat.Name) //fmt.Println("cat的地址是", &cat)
var p1 Person
fmt.Println("p1=", p1) //都是空
if p1.prt == nil {
fmt.Println("空指针")
}
if p1.Adress == nil {
fmt.Println("空切片")
}
if p1.Score == nil {
fmt.Println("空map")
}
//使用slice,要先make
p1.Adress = make([]string, 10)
p1.Adress[0] = "朝阳区劲松街道"
//使用map,要先make
p1.Score = make(map[string]int, 2)
p1.Score["数学"] = 100
p1.Score["语文"] = 98
p1.Score["英语"] = 90
p1.Name = "tom"
fmt.Println(p1)
p2 := p1
p2.Name = "lili"
fmt.Println(p2)
fmt.Println(p1) //结构体是值拷贝,不同结构体的值类型是独立的,互不影响
}
/* 结构体是一种数据类型,相当于其他语言的类 */
//结构体指针 package main
import ( "fmt" _ "fmt" )
type Dog struct { Name string Age int }
func main() {
var dog Dog
dog.Name = "ton"
dog.Age = 3
//dog2的值就是dog的地址,这是指针的定义
var dog2 *Dog = &dog
fmt.Println((*dog2).Age)
fmt.Println(dog2.Age)
dog2.Name = "Mary"
fmt.Println(dog2.Name, dog.Name)
fmt.Println((*dog2).Name, dog.Name)
fmt.Printf("dog的地址为%p \n", &dog)
fmt.Printf("dog2的地址为%p dog2的直为%p\n", &dog2, dog2)
}