代码改变世界

golang error (slice of unaddressable value)

2017-12-18 19:05  DillGao  阅读(1516)  评论(0编辑  收藏  举报

使用 Golang 将生成的 md5 转化为 string 的过程出现如下编译错误:

错误解析:

  值得注意的一点是  func Sum(data []byte) [Size]byte  这个函数返回的结果是数组(array)而不是切片(slice)。

  用下面的例子说明,编译错误的那行是因为 [3]int{1,2,3} 没有赋值给任何变量的时候,编译器是不知道它的地址的,因此编译到 [:] 时会报错。解决的办法就是将 [3]int{1,2,3} 赋值给一个变量,然后再对这个变量切片。

dill$ go run test.go
# command-line-arguments
./test.go:5:20: invalid operation [3]int literal[:] (slice of unaddressable value)
dill$ cat test.go
package main
import "fmt"

func main(){
    b := [3]int{1,2,3}[:] // compile error
    //b := [3]int{1,2,3} // works
    c := b[:] // works
    fmt.Println(c[0])
}