2 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個贊
用作interface{}參數(shù)類型。類型斷言指針類型。取消引用指針以設(shè)置值。
func UpdateRef(variadic ...interface{}) {
for _, v := range variadic {
if v, ok := v.(*string); ok {
*v = "New ref val"
}
}
}
將指針傳遞給函數(shù):
ref := "Hey"
i := 500
UpdateRef(&ref, &i)
fmt.Println(ref) // prints “New ref val”

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個贊
你剛才
package main
import (
"reflect"
)
// back-end
func UpdateRef(variadic ...interface{}) {
for _, v := range variadic {
kind := reflect.TypeOf(v).Kind()
if kind == reflect.Pointer {
reflect.ValueOf(v).Elem().Set(reflect.ValueOf("New ref val"))
}
}
}
// front-end
func main() {
ref := "Hey" // starts as "Hey"
// To modify a reflection object, the value must be settable.
UpdateRef(&ref, 500) // ends at "New ref val"
println(ref)
}
查看 golang 博客:https ://go.dev/blog/laws-of-reflection 。
編碼快樂!
- 2 回答
- 0 關(guān)注
- 105 瀏覽
添加回答
舉報