Golang在函数中给结构体对象赋值的一个坑

错误的赋值方式

package z_others

import (
    "fmt"
    "testing"
)

type Student struct {
    Name   string
    Age    int
    Gender string
}

func GenStudent(stuObj *Student) {

    s := Student{
        Name:   "whw",
        Age:    22,
        Gender: "male",
    }
    // 这样赋值,不会改变实参!!!
    stuObj = &s
}

func TestTS(t *testing.T) {

    var s1 Student
    GenStudent(&s1)
    fmt.Println("s1>>> ", s1, s1.Name, s1.Age, s1.Gender)
    // s1>>>  { 0 }  0

正确的赋值方式

package z_others

import (
    "fmt"
    "testing"
)

type Student struct {
    Name   string
    Age    int
    Gender string
}

func GenStudent(stuObj *Student) {

    s := Student{
        Name:   "whw",
        Age:    22,
        Gender: "male",
    }
    // 正确的赋值方式
    *stuObj = s
}

func TestTS(t *testing.T) {

    var s1 Student
    GenStudent(&s1)
    fmt.Println("s1>>> ", s1, s1.Name, s1.Age, s1.Gender)
    // s1>>>  {whw 22 male} whw 22 male
}

也可以直接在函数中修改结构体对象的属性-结构体是引用类型

func EditStu(stu *Student, newName, newGender string, newAge int) *Student {

    stu.Name = newName
    stu.Gender = newGender
    stu.Age = newAge

    return stu
}

func TestTS2(t *testing.T) {

    s := Student{
        Name:   "whw",
        Age:    22,
        Gender: "male",
    }

    EditStu(&s, "naruti", "male", 23)

    fmt.Println("newS>>> ", s) // newS>>>  {naruti 23 male}

}

~~~

posted on 2021-11-14 14:27  江湖乄夜雨  阅读(1650)  评论(0编辑  收藏  举报