golang复制一个指针对象(反射)
package main import ( "fmt" "reflect" ) type User struct { Name string Age int } func copyPoint(m *User) *User{ vt := reflect.TypeOf(m).Elem() fmt.Println(vt) newoby := reflect.New(vt) newoby.Elem().Set(reflect.ValueOf(m).Elem()) return newoby.Interface().(*User) } func main(){ user := &User{} user.Name = "sunlong" user.Age = 32 fmt.Println(user) fmt.Printf("%p \n",user) user2 := copyPoint(user) fmt.Printf("%p \n",user) fmt.Printf("%p \n",user2) user.Name="lisi" fmt.Printf("%v \n",user) fmt.Printf("%v \n",user2) return //user2 := *user //fmt.Printf("%v \n",user) //fmt.Printf("%v \n",user2) //user2.Age = 33 //user2.Name = "lisi" //fmt.Println(*user) //fmt.Println(user2) }
&{sunlong 32} 0xc000004480 main.User 0xc000004480 0xc0000044e0 &{lisi 32} &{sunlong 32}
相关推荐
Android开发CXY 2020-11-11
lpkwxl 2020-06-17
RealJianyuan 2020-06-14
pbyanglove 2020-06-09
徐建岗网络管理 2020-06-09
fengjing81 2020-06-06
lynjay 2020-06-02
吴小伟 2020-05-09
sillion 2020-05-03
xiaobater 2020-05-01
ericasadun 2020-04-26
lynjay 2020-04-26
choupiaoyi 2020-04-26
tydldd 2020-04-23
拉斯厄尔高福 2020-04-22