1 回答

TA貢獻2051條經驗 獲得超10個贊
你到底想要什么?您想更新傳遞給的變量Execute()嗎?
如果是這樣,您必須將指針傳遞給Execute(). 然后你只需要傳遞reflect.ValueOf(incrementedValue).Interface()給Scan(). 這是有效的,因為reflect.ValueOf(incrementedValue)是一個reflect.Value持有一個interface{}(您的參數的類型),它持有一個指針(您傳遞給的指針Execute()),Value.Interface()并將返回一個interface{}持有指針的類型的值,您必須傳遞的確切內容Scan()。
請參閱此示例(使用fmt.Sscanf(),但概念相同):
func main() {
i := 0
Execute(&i)
fmt.Println(i)
}
func Execute(i interface{}) {
fmt.Sscanf("1", "%d", reflect.ValueOf(i).Interface())
}
它將1從打印main(),因為該值1設置在 內Execute()。
如果您不想更新傳遞給 的變量Execute(),只需創建一個具有相同類型的新值,因為您使用的reflect.New()是返回Value指針的 ,您必須傳遞existingObj.Interface()返回一個interface{}持有指針的指針,您想要的東西傳遞給Scan(). (你所做的是你傳遞了一個指向 a 的指針reflect.Value,Scan()這不是所Scan()期望的。)
演示fmt.Sscanf():
func main() {
i := 0
Execute2(&i)
}
func Execute2(i interface{}) {
o := reflect.New(reflect.ValueOf(i).Elem().Type())
fmt.Sscanf("2", "%d", o.Interface())
fmt.Println(o.Elem().Interface())
}
這將打印2.
的另一個變體Execute2()是,如果您直接調用Interface()由 返回的值reflect.New():
func Execute3(i interface{}) {
o := reflect.New(reflect.ValueOf(i).Elem().Type()).Interface()
fmt.Sscanf("3", "%d", o)
fmt.Println(*(o.(*int))) // type assertion to extract pointer for printing purposes
}
這Execute3()將按3預期打印。
嘗試Go Playground上的所有示例。
- 1 回答
- 0 關注
- 159 瀏覽
添加回答
舉報