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 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler