2 回答

TA贡献1786条经验 获得超11个赞
它无法工作,因为您尝试将 AccessKey 附加到不是切片的 interface{} 类型。
package main
import (
"fmt"
)
type AccessKeys struct {
AccessKeys []interface{}
}
type AccessKey struct {
AccessKeyID string
}
func main() {
var b AccessKey
b.AccessKeyID = "ye"
var bs AccessKeys
bs.AccessKeys = append(bs.AccessKeys, b)
fmt.Println(bs)
}
但在我看来,这不是非常惯用的做某事的方式,而是取决于你想要实现的目标。我什至会替换
AccessKeys []interface{}
与
AccessKeys []AccessKey

TA贡献1796条经验 获得超7个赞
感谢一位后来删除他的评论的好心的海报。
它不起作用,因为AccessKeys interface{}
使 AccessKeys 成为无类型的 nil 类型,因为接口的零值是无类型的nil。由于 Go 是一种静态类型语言,它会在编译时报错。
如果这是有道理的,出于同样的原因,你不能在 Go 中这样做:
n := nil
即使这是固定的,它也会在运行时在断言 say 时失败panic: interface conversion: interface {} is nil, not []main.AccessKey
。虽然我不确定为什么。
- 2 回答
- 0 关注
- 124 浏览
添加回答
举报