package main
import (
"fmt"
"reflect"
)
func main() {
arr := []int{}
var arrI interface{} = arr
arrValuePtr := reflect.ValueOf(&arrI)
arrValue := arrValuePtr.Elem()
fmt.Println("Type: ", arrValue.Type()) // prints: "Type: interface{}
fmt.Println("Interface value: ", arrValue.Interface()) // prints: "Interface value: []"
arrValue.Set(reflect.Append(arrValue, reflect.ValueOf(55)))
// error: panic: reflect: call of reflect.Append on interface Value
}
那麼,有沒有認識到arrValue是切片值,而不是接口{}值的方法嗎? https://play.golang.org/p/R_sPR2JbQx
爲什麼要採用'interface {}'的指針? 'arrValue:= reflect.ValueOf(arrI)'給我'類型:int []':https://play.golang.org/p/5L1NqItNh1 – myaut
讓我們從這個例子開始:https://play.golang。組織/ p/Nhabg31Sju。在這個例子中,如果我不將arr作爲指針傳遞,我會在appendToSlice方法內部得到「reflect.Value.Set using unaddressable value」。 現在我想概括一下這個解決方案。我想將任何切片傳遞給此方法(忽略只添加int的事實)。更新示例:https://play.golang.org/p/WGtfjpW0EN – agnor