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
+3.3k Javascript : Empty an array example
+61.4k Golang : Convert HTTP Response body to string
+14.7k Golang : Update database with GORM example
+4.8k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+7k Golang : Randomize letters from a string example
+22.7k Golang : Upload to S3 with official aws-sdk-go package
+7.1k Golang : Find relative luminance or color brightness
+27.8k Golang : Save map/struct to JSON or XML file
+14.7k Golang : Read a file line by line
+11.3k Golang : Sort and reverse sort a slice of bytes
+4k Google : Block or disable caching of your website content