• 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}
    
    }

    ~~~

  • 相关阅读:
    虚树
    最小树形图
    分块
    斜率优化
    单调队列优化DP
    树套树
    2-SAT
    莫队
    单调队列
    单调栈
  • 原文地址:https://www.cnblogs.com/paulwhw/p/15551745.html
Copyright © 2020-2023  润新知