14.struct

示例代码

struct1.go

package chapter11

import "fmt"

// 声明一种数据类型 myInt, 是 int 的一个别名
type myInt int

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

// 作为值传递,函数的变动,不会影响到函数外
func changeBook1(book Book) {
    book.auth = "Jack"
}

// 形式采用引用传递,对象值的变化会作用待函数外
func changeBook2(book *Book) {
    book.auth = "Tom"
}

func Run() {

    var a myInt = 10
    fmt.Println("a = ", a)
    fmt.Printf("type of a = %T\n", a)

    // 结构体的使用
    var book1 Book
    book1.title = "Golang"
    book1.auth = "sam"

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

    // 函数 值传递
    fmt.Println("changeBook1-----值传递")
    changeBook1(book1)
    fmt.Printf("值传递的情况 book1 = %v\n", book1)

    // 函数 引用传递
    fmt.Println("changeBook2-----引用传递")
    changeBook2(&book1)
    fmt.Printf("引用传递的情况 book1 = %v\n", book1)
}

struct_test.go

package chapter11

import "testing"

func TestRun(t *testing.T) {
    Run()
}

执行结果

=== RUN   TestRun
a =  10
type of a = chapter11.myInt
book1 = {Golang sam}
changeBook1-----值传递
值传递的情况 book1 = {Golang sam}
changeBook2-----引用传递
引用传递的情况 book1 = {Golang Tom}
--- PASS: TestRun (0.00s)
PASS
ok      

2.总结

  • 结构体 声明 公式 type ${结构体的名称} struct { ,其中 typestruct 都是关键字
  • 结构做为函数的形参,注意区分是 值传递 还是 引用传递
posted @ 2021-10-08 16:40  可可逗豆  阅读(62)  评论(0)    收藏  举报