doupai1876 2017-12-18 19:48
浏览 49
已采纳

如何将struct的切片作为函数的指针传递并对其进行修改?

I have a slice of struct []student, and I want to modify its content with function.

type student struct {
    name string
    age int
}

students := []student{
    {"Doraemon", 30},
    {"King Kong", 25},
}

Thus, I decided to pass it as a pointer. May I know how to pass the slice as a reference to a function?

func addAge (s *[]student) error { //this code has error
    //everyone add 2 years old
    for i, e := range *s {
        s[i].age = s[i].age + 2
    }
    //make the first student much older
    s[0].age = s[0].age + 5
    return nil
}

I keep playing with Go Playground, but it gives many complains, such as

cannot range over s (type *[]student)
invalid operation: s[i] (type *[]student does not support indexing)
invalid indirect of s
...

How to precisely pass the reference of a slice of struct to a function? How to range the slice of struct? And how to change the value of the struct (modify the same struct in THE slice)?

I keep getting error while playing with s *[]student, range *s, s []student, s *[]*student ... so hard to get it correct...

sorry for my NEWBIE question, still learning GO... trying hard

  • 写回答

2条回答 默认 最新

  • dpleylxzx47207117 2017-12-18 20:33
    关注

    Slices are passed by reference, so as long as you are modifying the existing slice content you should not explicitly pass a pointer.

    package main
    
    import (
        "fmt"
    )
    
    type student struct {
        name string
        age int
    }
    
    func main() {
        students := []student{
            {"Doraemon", 30},
            {"King Kong", 25},
        }
    
        err := addAge (students)
    
        fmt.Println(students)
        if err != nil {
            fmt.Println("error")
        }
    }
    
    func addAge (s []student) error {
        for i, _ := range s {
            s[i].age = 3
        }
        return nil
    }
    

    Now, for your addAdditinalStudent function you should actually use the append function. Plus, have in mind

    ..., since the slice header is always updated by a call to append, you need to save the returned slice after the call. In fact, the compiler won't let you call append without saving the result. Slices#append

    // add student
    students = append(students, student{"Test", 33})
    

    Go Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化