英文:
How to copy/clone an interface pointer?
问题
我正在尝试复制一个作为interface{}接收的指针。有什么办法可以做到这一点吗?我尝试了Reflect.Value.Interface(),但它返回的是指针/地址本身,而不是返回其值(解引用)。我还想知道在进行这种复制与简单指针解引用之间是否存在显著的性能损失。
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)
}
你可以在这里查看代码:http://play.golang.org/p/rFmJGrLVaa
英文:
I'm trying to make a copy of a pointer received as interface{}. Any idea how to do that? I've tried Reflect.Value.Interface() but it returns the pointer/ address itself instead to return its value (deference). I'm also wondering if there is a signifiant performance loss as I'm planning doing this kind of copy vs simple pointer 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)
}
答案1
得分: 5
你需要使用reflect.Indirect
函数,并在修改s.field
之前设置b
的值。
以下是一段可工作的代码:
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)
}
你可以在这里查看代码:https://play.golang.org/p/PShhvwXjdG
英文:
You need reflect.Indirect, and also to set b
before changing s.field
.
Here is some working code :
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论