【发布时间】:2015-11-30 14:59:09
【问题描述】:
在我的程序中,我得到了 2 个模型:
type User struct {
Name string
}
type Article struct {
Title string
}
我得到了这些结构的数据数组:
users := []User
articles := []Article
我正在尝试在同一段代码中迭代它们:
models := [][]interface{} {users, articles}
for _, model := range models {
log.Printf("%#v", model)
}
但我收到一个错误:
cannot use users (type []User) as type []interface {} in array element
我做错了什么?
【问题讨论】:
-
这无法完成。 Go 是静态类型的。重新设计您的解决方案。
-
您无法将任何切片转换为
[]interface{}。有关解释和解决方案,请参阅Type converting slices of interfaces in go。 -
@Volker,icza 谢谢大家。
-
@WhiteAngel “go way”正在使用接口,我发布了一个可能有帮助的解决方案:)