首页后端开发GOgo的数据类型-复合数据类型-struct(三)

go的数据类型-复合数据类型-struct(三)

时间2023-04-26 12:45:01发布访客分类GO浏览1334
导读:嵌套结构体在Go中,我们可以在结构体类型中嵌套其他结构体类型,从而创建更复杂的数据结构。嵌套结构体的定义方式与普通结构体类型相同,只需将另一个结构体类型的名称作为字段的类型即可。以下是一个示例,其中定义了一个Address结构体类型,用于存...

嵌套结构体

在Go中,我们可以在结构体类型中嵌套其他结构体类型,从而创建更复杂的数据结构。嵌套结构体的定义方式与普通结构体类型相同,只需将另一个结构体类型的名称作为字段的类型即可。

以下是一个示例,其中定义了一个Address结构体类型,用于存储地址信息,另一个PersonWithAddress结构体类型,包含Person结构体和Address结构体:

type Address struct {

    City    string
    Country string
}


type PersonWithAddress struct {

    Person
    Address
}

在该示例中,PersonWithAddress结构体中包含了一个Person结构体和一个Address结构体。这样就可以通过一个变量来表示一个人的基本信息和地址信息。

我们可以使用以下代码来创建一个PersonWithAddress结构体类型的值:

personWithAddress := PersonWithAddress{

    Person: Person{
Name: "Alice", Age: 32}
,
    Address: Address{
City: "Beijing", Country: "China"}
,
}

这将创建一个名为personWithAddress的变量,并将其初始化为一个包含PersonAddress信息的结构体。

我们可以通过以下方式访问PersonWithAddress结构体类型的字段:

package main

import "fmt"

type Person struct {

    Name string
    Age  int
}


func (p Person) PrintInfo() {

    fmt.Printf("Name: %s, Age: %d\n", p.Name, p.Age)
}


func (p *Person) SetAge(age int) {

    p.Age = age
}


type Address struct {

    City    string
    Country string
}


type PersonWithAddress struct {

    Person
    Address
}


func main() {

    person := Person{
Name: "Alice", Age: 31}

    person.PrintInfo()
    person.SetAge(32)
    fmt.Printf("Name: %s, Age: %d\n", person.Name, person.Age)

    personWithAddress := PersonWithAddress{

        Person: Person{
Name: "Alice", Age: 32}
,
        Address: Address{
City: "Beijing", Country: "China"}
,
    }

    fmt.Printf("Name: %s, Age: %d, City: %s, Country: %s\n",
        personWithAddress.Person.Name,
        personWithAddress.Person.Age,
        personWithAddress.Address.City,
        personWithAddress.Address.Country)
}
    

输出结果:

Name: Alice, Age: 31
Name: Alice, Age: 32
Name: Alice, Age: 32, City: Beijing, Country: China

在这个示例中,我们首先定义了Person结构体类型,并定义了一个PrintInfo方法和一个SetAge方法,用于打印Person结构体类型的信息和设置Age字段的值。然后,我们定义了一个Address结构体类型,用于存储地址信息。最后,我们定义了一个PersonWithAddress结构体类型,它包含了Person结构体和Address结构体。

main函数中,我们首先创建一个Person结构体类型的值,并调用PrintInfo方法和SetAge方法来输出和修改Person结构体类型的信息。然后,我们创建一个PersonWithAddress结构体类型的值,并使用结构体字段的访问方式来输出PersonWithAddress结构体类型的信息。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

go

若转载请注明出处: go的数据类型-复合数据类型-struct(三)
本文地址: https://pptw.com/jishu/9238.html
go的数据类型-其他数据类型-pointer(二) go的数据类型-复合数据类型-struct(一)

游客 回复需填写必要信息