[英]what's the difference between `reflect.ValueOf(&x).Elem` and `reflect.ValueOf(x)` in go?
[英]What is the difference between reflect.ValueOf() and Value.Elem() in go?
幾天前我開始學習 golang,發現reflect.Valueof()和Value.Elem()很混亂。 這兩個函數/方法有什么區別以及如何正確使用它們?
兩個函數/方法都返回一個值,並根據 go doc
ValueOf 返回一個初始化為接口 i 中存儲的具體值的新值。 ValueOf(nil) 返回零值。
Elem 返回接口 v 包含的值或指針 v 指向的值。 如果 v 的 Kind 不是 Interface 或 Ptr,它會發生恐慌。 如果 v 為零,則返回零值。
我從 stackoverflow 上的一篇文章中找到了這段代碼,但仍然不明白何時使用 .Elem()
func SetField(obj interface{}, name string, value interface{}) error {
// won't work if I remove .Elem()
structValue := reflect.ValueOf(obj).Elem()
structFieldValue := structValue.FieldByName(name)
if !structFieldValue.IsValid() {
return fmt.Errorf("No such field: %s in obj", name)
}
if !structFieldValue.CanSet() {
return fmt.Errorf("Cannot set %s field value", name)
}
structFieldType := structFieldValue.Type()
// won't work either if I add .Elem() to the end
val := reflect.ValueOf(value)
if structFieldType != val.Type() {
return fmt.Errorf("Provided value %v type %v didn't match obj field type %v",val,val.Type(),structFieldType)
}
structFieldValue.Set(val)
return nil
}
reflect.ValueOf()
是一個函數,可以將其視為反射的入口點。 當您有一個“非反射”值時,例如string
或int
,您可以使用reflect.ValueOf()
來獲取它的reflect.Value
描述符。
Value.Elem()
是reflect.Value
一種方法。 所以你只能在你已經有一個reflect.Value
下使用它。 您可以使用Value.Elem()
來獲取由原始reflect.Value
包裹的值所指向的值( reflect.Value
)。 請注意,您也可以reflect.Indirect()
使用reflect.Indirect()
。 Value.Elem()
還有另一個“用例”,但它更“高級”,我們在答案的最后再回到它。
要“離開”反射,您可以使用通用的Value.Interface()
方法,該方法將包裝的值作為interface{}
。
例如:
var i int = 3
var p *int = &i
fmt.Println(p, i)
v := reflect.ValueOf(p)
fmt.Println(v.Interface()) // This is the p pointer
v2 := v.Elem()
fmt.Println(v2.Interface()) // This is i's value: 3
這將輸出(在Go Playground上嘗試):
0x414020 3
0x414020
3
有關 Go 反射的精彩介紹,請閱讀Go 博客:反射法則。 盡管如果您剛開始使用 Go,我會專注於其他事情,並將反思留給以后的冒險。
Value.Elem()
另一個用例這是一個高級話題,所以如果你不理解它,不要害怕。 你不需要。
我們看到了Value.Elem()
如何在一個指針被包裹在reflect.Value
時用於“導航”。 Value.Elem()
Doc 說:
Elem 返回接口 v 包含的值或指針 v 指向的值。
因此,如果reflect.Value
包裝了一個接口值, Value.Elem()
也可用於獲取包裝在該接口值中的具體值。
Go 中的接口是它自己的主題,對於內部結構,您可以閱讀Go Data Structures: Interfaces by Russ Cox。 同樣,不一定是 Go 初學者的主題。
基本上你傳遞給reflect.ValueOf()
任何值,如果它不是接口值,它將被隱式包裝在interface{}
。 如果傳遞的值已經是接口值,那么存儲在其中的具體值將作為interface{}
傳遞。 如果您將指針傳遞給接口(否則這在 Go 中非常罕見!),第二個“用例”就會浮出水面。
所以如果你傳遞一個指向 interface 的指針,這個指針將被包裝在一個interface{}
值中。 您可以使用Value.Elem()
獲取指向值,該值將是一個接口值(不是具體值),再次使用Value.Elem()
將為您提供具體值。
這個例子說明了它:
var r io.Reader = os.Stdin // os.Stdin is of type *os.File which implements io.Reader
v := reflect.ValueOf(r) // r is interface wrapping *os.File value
fmt.Println(v.Type()) // *os.File
v2 := reflect.ValueOf(&r) // pointer passed, will be wrapped in interface{}
fmt.Println(v2.Type()) // *io.Reader
fmt.Println(v2.Elem().Type()) // navigate to pointed: io.Reader (interface type)
fmt.Println(v2.Elem().Elem().Type()) // 2nd Elem(): get concrete value in interface: *os.File
在Go Playground上試一試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.