錯誤的賦值方式
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} }
~~~