Golang : Clone with pointer and modify value
For those familiar with C language and learning Golang, bear in mind that Golang supports pointer. In this short tutorial, we will learn how to create a struct tied to pointer, how to clone and manipulated the struct data with the pointer(second := *first
).
The code example below should be self explanatory. Should you have any question, please leave a comment below.
package main
import (
"fmt"
)
type User struct {
Id int
Name string
}
func createUser() *User {
newUser := new(User)
newUser.Id = 1
newUser.Name = "Adam"
return newUser
}
func main() {
// create our first user
first := createUser()
fmt.Printf("first user id is %d and name is %s\n", first.Id, first.Name)
// clone first user to second user
second := *first
// data are cloned as well
fmt.Printf("second user id is %d and name is %s\n", second.Id, second.Name)
// now modify second user's name and id
second.Id = 2
second.Name = "Victoria"
fmt.Printf("[modified] second user id is %d and name is %s\n", second.Id, second.Name)
}
Output :
first user id is 1 and name is Adam
second user id is 1 and name is Adam
[modified] second user id is 2 and name is Victoria
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+25.5k Golang : Convert long hexadecimal with strconv.ParseUint example
+9.5k Golang : Generate EAN barcode
+5.6k Clean up Visual Studio For Mac installation failed disk full problem
+4.8k Facebook : How to place save to Facebook button on your website
+4.9k Unix/Linux : secure copying between servers with SCP command examples
+9.9k Random number generation with crypto/rand in Go
+10.7k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+15.4k nginx: [emerg] unknown directive "ssl"
+6.9k Golang : Get expvar(export variables) to work with multiplexer
+9.1k Golang : Capture text return from exec function example
+18.8k Golang : Implement getters and setters