我正在尝试将接收的指针复制为接口{}.知道怎么做吗?我已经尝试过Reflect.Value.Interface()但它返回指针/地址本身而不是返回它的值(deference).我也想知道是否存在显着的性能损失,因为我计划进行这种复制与简单的指针干扰.
package main
import "fmt"
import "reflect"
type str struct {
field string
}
func main() {
s := &str{field: "astr"}
a := interface{}(s)
v := reflect.ValueOf(a)
s.field = "changed field"
b := v.Interface()
fmt.Println(a, b)
}
Run Code Online (Sandbox Code Playgroud)
您需要reflect.Indirect,并且还需要b在更改之前进行设置s.field。
这是一些工作代码:
https://play.golang.org/p/PShhvwXjdG
package main
import "fmt"
import "reflect"
type str struct {
field string
}
func main() {
s := &str{field: "astr"}
a := interface{}(s)
v := reflect.Indirect(reflect.ValueOf(a))
b := v.Interface()
s.field = "changed field"
fmt.Println(a, b)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
757 次 |
| 最近记录: |