1 回答
TA貢獻1828條經驗 獲得超6個贊
反映。類型有一個方法:Type.AssignableTo()
// AssignableTo reports whether a value of the type is assignable to type u.
AssignableTo(u Type) bool
因此,您可以使用它來簡化您的函數:set()
func set(v reflect.Value, i interface{}) bool {
if !reflect.TypeOf(i).AssignableTo(v.Type()) {
return false
}
v.Set(reflect.ValueOf(i))
return true
}
輸出將相同(在Go Playground上嘗試):
After o1 set to aInt returned true: obj is type int content '456'
After o1 set to aString returned false: obj is type int content '456'
After o1 set to aUint returned false: obj is type int content '456'
After o2 set to aInt returned true: obj is type int content '456'
After o2 set to aString returned true: obj is type string content 'hello'
After o2 set to aUint returned true: obj is type uint content '123'
您也可以(另外)調用 Value.CanSet() 來檢測某些“不可設置”的情況:
可以設置報告是否可以更改 v 的值。僅當 Value 可尋址且未通過使用未導出的結構字段獲取時,才能更改該值。如果 CanSet 返回 false,則調用 Set 或任何特定于類型的 setter(例如,SetBool、SetInt)將會死機。
- 1 回答
- 0 關注
- 112 瀏覽
添加回答
舉報
