- 定义结构体
package mainimport "fmt"type Person struct {age, id intname, email string
}func main() {var p Personfmt.Printf("p: %v\n", p)p.age = 100p.name = "jaja"fmt.Printf("p.name: %v\n", p.name)// 匿名结构体var Pp struct {age, id intname, email string}Pp.age = 100fmt.Printf("Pp.age: %v\n", Pp.age)
}
- 结构体初始化
未被初始化的结构体string类型默认为nil,int类型默认为0,bool类型默认为false
package mainimport "fmt"type Person struct {age, id intname, email string
}func main() {var p Personfmt.Printf("p: %v\n", p)fmt.Printf("p.name: %v\n", p.name)// 使用键值对初始化p = Person{name: "haha"}fmt.Printf("p.name: %v\n", p.name)//使用顺序初始化,所有的键必须赋值p = Person{1, 1, "haha", "haha"}fmt.Printf("p: %v\n", p)
}
- 结构体指针
package mainimport "fmt"type Person struct {name, email string
}func main() {var p_person Person = Person{name: "tom",email: "tom@qq.com",}var p *Personp = &p_personfmt.Printf("p: %v\n", p)fmt.Printf("p.name: %v\n", p.name)p.email = "haha"fmt.Printf("p_person: %v\n", p_person)fmt.Printf("p: %v\n", p)}
、、使用new关键字创建一个指针
package mainimport "fmt"type Person struct {name, email string
}func main() {p_person := new(Person)p_person.email = "haha"fmt.Printf("p_person: %v\n", p_person)}
- 结构体当成函数参数
package mainimport "fmt"type Person struct {name, email string
}//值传递结构体
func showInfo(person Person) {person.email = "dalian@qq.com"person.name = "dalian"fmt.Printf("person: %v\n", person)
}func structShow(person *Person) {person.email = "dalian@qq.com"person.name = "dalian"fmt.Printf("person: %v\n", person)
}func main() {var p_person Person = Person{name: "tom",email: "tom@qq.com",}fmt.Printf("p_person: %v\n", p_person)showInfo(p_person)fmt.Printf("p_person: %v\n", p_person)structShow(&p_person)fmt.Printf("p_person: %v\n", p_person)}