6 回答

TA貢獻1853條經驗 獲得超6個贊
reflect
?涉及包的解決方案。
package main
import (
? ? "fmt"
? ? "reflect"
)
func main() {
? ? var v interface{} = []string{"a", "b", "c"}
? ? var out []interface{}
? ? rv := reflect.ValueOf(v)
? ? if rv.Kind() == reflect.Slice {
? ? ? ? for i := 0; i < rv.Len(); i++ {
? ? ? ? ? ? out = append(out, rv.Index(i).Interface())
? ? ? ? }
? ? }
? ? fmt.Println(out)
}
// Output:
// [a b c]

TA貢獻1786條經驗 獲得超11個贊
我現在實際上正在處理這個問題,因為我的問題涉及從 json 對象 (map[string]interface{}) 中獲取一些東西,它可能包含也可能不包含特定的鍵 ({"someKey": [a, b, c, ...]),如果它確實包含那個鍵,那么我們想要獲取那個(它必然是 interface{} 類型)并將其轉換為 []interface{}。到目前為止我找到的方法是使用 json marshall/unmarshall。

TA貢獻1821條經驗 獲得超5個贊
type a map[string]interface{}
type b []string
func main() {
obj := a{
"someKey": b{"a", "b", "c"},
}
if obj["someKey"] != nil { // check the value exists
var someArr []interface{}
//marshal interface to byte and then unmarshal to []interface{}
somebytes, _ := json.Marshal(obj["someKey"])
err := json.Unmarshal(somebytes, &someArr)
if err != nil {
fmt.Println("Error in unmarshal")
}
fmt.Println(someArr)
}
}

TA貢獻1951條經驗 獲得超3個贊
我該如何進行轉換?(如果可能,不反映)。
請考慮類型開關。
反射是昂貴的。
func toSlice(i interface{}) []interface{} {
var out []interface{}
switch v := i.(type) {
case []interface{}:
for x := 0; x < len(v); x++ {
out = append(out, v[x])
}
default:
fmt.Printf("invalid type: %T\n", v)
}
return out
}

TA貢獻2021條經驗 獲得超8個贊
接口的重點是定義你想要使用的行為,如果你使用一個空接口,你對那個切片中的類型一無所知。
如果你想打印它,你可以使用 println 或 printf 沒有轉換。
如果你想訪問它,并且必須允許任何類型,你可以使用反射(使用起來緩慢且復雜)。
如果您想訪問它,并使用可以為其定義函數的常見行為/數據,請定義一個接口,例如:
type Doer interface {
Do() error
}
parentStruct := []Doer{...}
testStruct.Do()
如果這些都不起作用,請等待 Go 2 和泛型。

TA貢獻1831條經驗 獲得超10個贊
對于任何在 2022 年發現這一點的人,現在我們有了仿制藥,您可以這樣做:
func convertSlice[T any](data []T) []interface{} {
output := make([]interface{}, len(data))
for idx, item := range data {
output[idx] = item
}
return output
}
- 6 回答
- 0 關注
- 221 瀏覽
添加回答
舉報