go语言学习之旅之Go结构体

在Go语言中,结构体(struct)是一种用户定义的数据类型,用于组合不同类型的数据项。结构体可以包含其他结构体或基本数据类型的字段。以下是关于Go语言结构体的基本知识:

定义结构体:

go 复制代码
package main

import "fmt"

// 定义一个结构体
type Person struct {
    FirstName string
    LastName  string
    Age       int
}

func main() {
    // 创建结构体实例
    person1 := Person{
        FirstName: "John",
        LastName:  "Doe",
        Age:       30,
    }

    // 访问结构体字段
    fmt.Println("First Name:", person1.FirstName)
    fmt.Println("Last Name:", person1.LastName)
    fmt.Println("Age:", person1.Age)
}

结构体的零值:

未初始化的结构体字段将使用它们的零值。对于字符串类型,零值是空字符串;对于数值类型,零值是0。

匿名结构体:

可以在使用的地方直接定义结构体,而不必显式声明结构体类型。

go 复制代码
package main

import "fmt"

func main() {
    // 匿名结构体
    person := struct {
        FirstName string
        LastName  string
        Age       int
    }{
        FirstName: "Jane",
        LastName:  "Doe",
        Age:       25,
    }

    fmt.Println("First Name:", person.FirstName)
    fmt.Println("Last Name:", person.LastName)
    fmt.Println("Age:", person.Age)
}

结构体方法:

可以在结构体上定义方法,这是一种在结构体上附加行为的方式。

go 复制代码
package main

import "fmt"

type Rectangle struct {
    Width  float64
    Height float64
}

// 定义结构体方法
func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

func main() {
    rectangle := Rectangle{
        Width:  10,
        Height: 5,
    }

    // 调用结构体方法
    area := rectangle.Area()
    fmt.Println("Area of the rectangle:", area)
}

嵌套结构体:

结构体可以包含其他结构体,形成嵌套结构体。

go 复制代码
package main

import "fmt"

type Address struct {
    City  string
    State string
}

type Person struct {
    FirstName string
    LastName  string
    Age       int
    Address   Address // 嵌套结构体
}

func main() {
    // 创建嵌套结构体实例
    person := Person{
        FirstName: "Alice",
        LastName:  "Smith",
        Age:       28,
        Address: Address{
            City:  "New York",
            State: "NY",
        },
    }

    // 访问嵌套结构体字段
    fmt.Println("First Name:", person.FirstName)
    fmt.Println("Last Name:", person.LastName)
    fmt.Println("Age:", person.Age)
    fmt.Println("City:", person.Address.City)
    fmt.Println("State:", person.Address.State)
}

这些是关于Go语言结构体的基本知识。结构体在Go语言中是一种强大的工具,用于组织和表示复杂的数据结构。

相关推荐
灯澜忆梦13 分钟前
GO_面向对象_方法
开发语言·golang
布朗克16820 分钟前
Go 入门到精通-16-字符串深入
开发语言·后端·golang·字符串
胡渠洋25 分钟前
postman学习
学习·测试工具·postman
北冥you鱼30 分钟前
Go flag 包详解:从命令行解析到实战应用
开发语言·后端·golang
小池先生34 分钟前
Windows服务器如何备份
运维·服务器
Amazing_Cacao2 小时前
CFCA精品可可产区风土解析(美洲):无情打破风味堆叠假象,建立时间轴上的层次动态阅读系统
学习
六点_dn2 小时前
Linux学习笔记-shell运算符
linux·笔记·学习
其实防守也摸鱼3 小时前
渗透--损坏的对象级别鉴权漏洞(Broken Object Level Authorization, BOLA)
大数据·网络·数据库·学习·tcp/ip·安全·安全威胁分析
sramdram3 小时前
数字温度传感器应用于服务器系统热管理方案的优势
服务器·温度传感器·数字温度传感器
hehelm3 小时前
IO 多路复用 — Reactor
linux·服务器·网络·数据库·c++