介绍结构体之前,首先要介绍type关键字,type关键字用来声明一种数据类型,也可以声明结构体。

例如:

package main

import "fmt"

// 声明一种新的数据类型myint,为int的一个别名
type myint int

func main() {
    var a myint = 10
    fmt.Println("a = ", a)
    fmt.Printf("type of a = %T\n", a)
}

运行结果:
image.png

定义结构体

package main

import "fmt"

// 定义一个结构体
type Book struct {
    title string
    author string
}

func changeBook1(book Book){
    // 传递一个book的副本,不共享内存空间
    book.author = "111"
}

func changeBook2(book *Book){
    // 指针传递
    book.author = "222"
}

func main() {
    //var a myint = 10
    //fmt.Println("a = ", a)
    //fmt.Printf("type of a = %T\n", a)
    var book1 Book
    book1.title = "回首掏"
    book1.author = "芜湖大司马"
    fmt.Printf("%v\n", book1)

    changeBook1(book1)
    fmt.Printf("%v\n", book1)

    changeBook2(&book1)
    fmt.Printf("%v\n", book1)

}
  • 6-9行定义一个结构体Book
  • 11-14行定义函数,将Book结构体作为参数,这里函数传递的是一个Book副本,与传入的不共享内存空间
  • 16-19行定义函数,将Book的指针作为参数,这样内部是引用传递,修改内部的参数值,函数体外的结构体也会有影响。

运行结果:
image.png
从结果可以总结出,当结构体直接作为参数传递给函数时,函数会复制一份副本再修改,函数外的结构体不变,而当结构体的指针传递给函数时,函数内部修改结构体会直接改变原先的结构体中的内容。

最后修改:2024 年 03 月 13 日
如果觉得我的文章对你有用,请随意赞赏