如何使用接口填充切片?

How do I populate a slice with interfaces?

我知道我可以用 strings := []string{"something", "something else"} 的字符串填充 Go slice,但是除了接口之外我该如何做呢?我尝试了以下方法:

data := []interface{}{{ID: "123"}, {ID: "456"}}

并得到以下错误:

missing type in composite literal

我也尝试过使用这样的结构:

type Users struct {
    ID string
}

[]Users{{ID: "123"}, {ID: "456"}}

有效,但是 mongoInsertMany 函数需要一个 []interface{} 参数:

cannot use users (type []Users) as type []interface {} in argument to database.InsertMany

如何定义和填充 []interface{}

如错误所述,您缺少复合文字中的类型:

data := []interface{}{Users{ID: "123"}, Users{ID: "456"}}

应该可以工作,因为它不会缺少复合文字中的类型。

[]interface{}[]Users 在 Go 中是不同的类型。

https://github.com/golang/go/wiki/InterfaceSlice

所以你可以像 Adrian 的回答那样初始化你的切片,或者你可以像这样从用户切片创建接口切片

users := []Users{{ID: "123"}, {ID: "456"}}
usersInterfaces := make([]interface{}, len(users))

for i, u := range users {
    usersInterfaces[i] = u
}