前端之家收集整理的这篇文章主要介绍了
010.golang 结构struct,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
结构struct
- Go 中的struct与C中的struct非常相似,并且Go没有class
- 使用
type <Name> struct{}
定义结构,名称遵循可见性规则
- 支持指向自身的指针类型成员
- 支持匿名结构,可用作成员或定义成员变量
- 匿名结构也可以用于map的值
- 可以使用字面值对结构进行初始化
- 允许直接通过指针来读写结构成员
- 相同类型的成员可进行直接拷贝赋值
- 支持 == 与 !=比较运算符,但不支持 > 或 <
- 支持匿名字段,本质上是定义了以某个类型名为名称的字段
- 嵌入结构作为匿名字段看起来像继承,但不是继承
- 可以使用匿名字段指针
package main
import (
"fmt"
)
type person struct {
Name string
Age int
}
func main() {
a := person{}
a.Age = 19
a.Name = "xiaoMing"
fmt.Println(a)
b := person{
Name: "daMing",
Age: 20,
}
fmt.Println(b)
b.Age = 23
fmt.Println(b)
updateAge(b)
fmt.Println(b,"new")
updateOrigenAge(&b)
fmt.Println(b,"new")
c := &person{
Name: "laoWang",
Age: 58,
}
fmt.Println(c)
c.Name = "xiaoWang"
updateOrigenAge(c)
fmt.Println(c,"new")
}
func updateAge(b person) {
b.Age = 3
fmt.Println(b,"updateAge")
}
func updateOrigenAge(b *person) {
b.Age = 5
fmt.Println(b,"updateOrigenAge")
}
package main
import (
"fmt"
)
type person struct {
Name string
Age int
Contact struct {
Phone,City string
}
}
func main() {
a := struct {
Name string
Age int
}{
Name: "xiaoMing",Age: 18,}
fmt.Println(a)
fmt.Println("----------------------")
b := person{
Name: "xiaoWang",}
b.Age = 19
b.Contact.City = "beiJing"
b.Contact.Phone = "894401224"
fmt.Println(b)
}
package main
import (
"fmt"
)
type person struct {
string
int
}
func main() {
a := person{"xiaoMing", 12}
fmt.Println(a)
}
package main
import (
"fmt"
)
type person struct {
Name string
Age int
}
func main() {
a := person{"xiaoMing", 12}
b := person{"xiaoMing", 13}
fmt.Println(b == a)
b.Age = 12
fmt.Println(b == a)
}
package main
import (
"fmt"
)
type human struct {
Sex int
}
type teacher struct {
human
Name string
Age int
}
type student struct {
human
Name string
Age int
}
func main() {
a := teacher{Name: "laoMing",Age: 48,human: human{Sex: 0}}
b := student{Name: "xiaoMing",Age: 18,human: human{Sex: 1}}
fmt.Println("a",a)
fmt.Println("b",b)
a.Name = "laoWang"
a.Age = 50
a.human.Sex = 1
fmt.Println("a",a)
}
package main
import (
"fmt"
)
type human struct {
Sex int
Name string
}
type student struct {
human
Name string
Age int
}
func main() {
a := student{Name: "laoMing",human: human{Sex: 0,Name: "lao.Ming"}}
b := student{Age: 18,human: human{Sex: 1,Name: "xiao.Ming"}}
c := student{Name: "xiao.Ming",human: human{Sex: 1}}
fmt.Println("a.Name=",a.Name,"|","a.human.Name=",a.human.Name)
fmt.Println("b.Name=",b.Name,"b.human.Name=",b.human.Name)
fmt.Println("c.Name=",c.Name,"c.human.Name=",c.human.Name)
}
原文链接:https://www.f2er.com/go/187110.html