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 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类