Golang教程-Go结构体

Go结构体
在Go中,结构体可以用来创建用户定义的类型。
结构体是一种复合类型,意味着它可以具有不同的属性,每个属性都可以有自己的类型和值。
结构体可以表示具有这些属性的现实世界实体。我们可以将属性数据作为一个单独的实体进行访问。它也是值类型,并可以使用new()函数进行构造。
Go结构体示例
package main
import (
"fmt"
)
type person struct {
firstName string
lastName string
age int
}
func main() {
x := person{age: 30, firstName: "John", lastName: "Anderson", }
fmt.Println(x)
fmt.Println(x.firstName)
}
输出:
{John Anderson 30}
John
Go嵌入结构体
结构体是一种数据类型,可以作为匿名字段(仅具有类型)使用。一个结构体可以被插入或"嵌入"到另一个结构体中。
这是一种简单的“继承”,可以用于实现从其他类型或类型中继承的实现。
Go嵌入结构体示例
package main
import (
"fmt"
)
type person struct {
fname string
lname string}
type employee struct {
person
empId int
}
func (p person) details() {
fmt.Println(p, " "+" I am a person")
}
func (e employee) details() {
fmt.Println(e, " "+"I am a employee")
}
func main() {
p1 := person{"Raj", "Kumar"}
p1.details()
e1 := employee{person:person{"John", "Ponting"}, empId: 11}
e1.details()
}
输出:
{Raj Kumar} I am a person
{{John Ponting} 11} I am a employee