douganbi7686 2012-05-24 15:04
浏览 30
已采纳

Go中关于`slice`和`append`的问题

I have written the following code. But I can't have it compiled. Here is my code:

package main

import "fmt"

func main() {
    tmp := make([]int, 10)
    for i := 0; i < 10; i++ {
        tmp[i] = i
    }
    res := mapx(foo, tmp)
    fmt.Printf("%v
", res)
}

func foo(a int) int {
    return a + 10
}

func mapx(functionx func(int) int, list []int) (res []int) {
    res = make([]int, 10)
    for _, i := range(list) {
        append(res, functionx(i))
    }
    return
}

Meanwhile the error message is also very confusing: prog.go:21: append(res, functionx(i)) not used

But if I replace append(res, functionx(i))(line 21) with res = append(res, functionx(i)), it works quite well. Can anybody help me?

Thank you!

  • 写回答

1条回答 默认 最新

  • dongyuan1870 2012-05-24 15:20
    关注

    Appending to and copying slices

    The variadic function append appends zero or more values x to s of type S, which must be a slice type, and returns the resulting slice, also of type S.

    If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large slice that fits both the existing slice elements and the additional values. Thus, the returned slice may refer to a different underlying array.

    Calls

    In a function call, the function value and arguments are evaluated in the usual order. After they are evaluated, the parameters of the call are passed by value to the function and the called function begins execution. The return parameters of the function are passed by value back to the calling function when the function returns.

    In Go, arguments are passed by value.

    You need to write res = append(res, functionx(i)) so that you don't discard the new value for res, which refers to a different slice and, possibly, a different underlying array.

    For example,

    package main
    
    import "fmt"
    
    func main() {
        res := []int{0, 1}
        fmt.Println(res)
        _ = append(res, 2) // discard
        fmt.Println(res)
        res = append(res, 2) // keep
        fmt.Println(res)
    }
    

    Output:

    [0 1]
    [0 1]
    [0 1 2]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答