有如果v
沒有差別是一個非空指針類型。
s := "hello"
rv := reflect.ValueOf(&s)
fmt.Println(rv.Type().Elem() == rv.Elem().Type()) // prints "true"
下面是一些例子,其中rv.Type().Elem()
和rv.Elem().Type())
是不同的:
// nil pointer
var p *string
rv := reflect.ValueOf(p)
fmt.Println(rv.Type().Elem()) // prints "string"
fmt.Println(rv.Elem().Type()) // panic: call of reflect.Value.Type on zero Value
// interface value
var i interface{} = "hello"
rv := reflect.ValueOf(&i).Elem()
fmt.Println(rv.Type()) // prints "interface {}"
fmt.Println(rv.Elem().Type()) // prints "string"
fmt.Println(rv.Type().Elem()) // panic: Elem of invalid type
如果rv.Type().Elem()
在Allocate
使用,那麼零檢查可以被移除,並且功能將與零指針值工作。
呼叫reflect.DeepEqual(s0, s1)
返回false,因爲值中的ptr fields不同。 DeepEqual
比較不安全的指針作爲簡單的值,而不是指針。這個例子可能有助於解釋這是怎麼回事:
v := "hello"
rv := reflect.ValueOf(&v)
s0 := reflect.New(rv.Type().Elem())
s1 := reflect.New(rv.Elem().Type())
s2 := reflect.New(rv.Type().Elem())
s3 := reflect.New(rv.Elem().Type())
fmt.Println(reflect.DeepEqual(s0, s1)) // prints "false"
fmt.Println(reflect.DeepEqual(s0, s2)) // prints "false"
fmt.Println(reflect.DeepEqual(s1, s3)) // prints "false"
fmt.Println(reflect.DeepEqual(s2, s3)) // prints "false"
fmt.Println(reflect.DeepEqual(s0.Interface(), s1.Interface())) // prints "true"
fmt.Println(reflect.DeepEqual(s0.Interface(), s2.Interface())) // prints "true"
fmt.Println(reflect.DeepEqual(s1.Interface(), s3.Interface())) // prints "true"
fmt.Println(reflect.DeepEqual(s2.Interface(), s3.Interface())) // prints "true"
正如你所看到的,reflect.Value比較全是假的,即使使用電話的同一序列創建時。
如果'v'是一個指針類型,我認爲沒有。 – Volker
我也不這麼認爲,但肯定有一些差異,因爲reflect.DeepEqual(s0,s1)返回false – Sridhar