zoukankan      html  css  js  c++  java
  • 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}
    
    }

    ~~~

  • 相关阅读:
    MapReduce-shuffle过程详解
    YARN中的失败分析
    HBase协处理器的使用(添加Solr二级索引)
    Flume具体应用(多案例)
    Flume架构及运行机制
    python Cmd实例之网络爬虫应用
    mongodb3 权限认证问题总结
    webpack配置
    apt软件包管理
    python笔记之编程风格大比拼
  • 原文地址:https://www.cnblogs.com/paulwhw/p/15551745.html
Copyright © 2011-2022 走看看