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}

}

~~~


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM