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