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
+11.5k Golang : GTK Input dialog box examples
+18.6k Golang : Padding data for encryption and un-padding data for decryption
+11.1k Golang : Characters limiter example
+5.1k Javascript : Shuffle or randomize array example
+13.4k Golang : Tutorial on loading GOB and PEM files
+6.2k Grep : How to grep for strings inside binary data
+7.4k Gogland : Where to put source code files in package directory for rookie
+9.9k Golang : Random Rune generator
+12.8k Golang : List objects in AWS S3 bucket
+8.5k Golang : Combine slices but preserve order example
+25.4k Golang : How to write CSV data to file
+15.6k Golang : Update database with GORM example