Golang中结构体指针内容拷贝

Golang struct pointer content copy

Posted by alovn on June 2, 2020

在go语言中比如一个指定内容复制到另外一个指针的内容中,实现非常简单:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main  

import "fmt"  
    
type Student struct {  
    Name string  
}  
    
func main() {  
    var a *Student = new(Student)  
    var b *Student  = &Student{Name: "aaa"}  
    
    *a = *b
    
    fmt.Println("a=", a, "b=", b)

    b.Name = "bbb"  
    fmt.Println("a=", a, "b=", b)  
}

// Output
// a= &{aaa} b= &{aaa}
// a= &{aaa} b= &{bbb}