golang复制一个指针对象(反射)

wujingsheng0 2020-05-16

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}

相关推荐

NewActivity / 0评论 2020-05-08
fengjing81 / 0评论 2020-01-23