Go Struct
Go Struct
在 Go 中,Struct 可用于创建用户定义的类型。
Struct 是一种复合类型意味着它可以具有不同的属性和每个属性都可以有自己的类型和值。
Struct 可以用这些属性表示现实世界的实体。我们可以将属性数据作为单个实体访问。它也是值类型,可以用 new() 函数构造。
Go Struct Example
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)
}
输出:
Go Embedded Struct
Struct 是一种数据类型,可以用作匿名字段(只有类型)。一个结构可以插入或"嵌入"到另一个结构中。
这是一个简单的"继承",可用于实现其他类型或类型的实现。
转到嵌入式结构示例
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