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
+5.9k Golang : Get all countries currencies code in JSON format
+6k Golang : On lambda, anonymous, inline functions and function literals
+7.7k Golang : Save webcamera frames to video file
+3.1k Python : Create Whois client or function example
+34k Golang : Marshal and unmarshal json.RawMessage struct example
+7.9k Golang : Simple File Server
+5.2k Golang : Check to see if *File is a file or directory
+7.8k Golang : Get user input until a command or receive a word to stop
+25.7k Golang : Download file example
+21.9k Golang : Detect (OS) Operating System
+19.1k Golang : Calculate percentage change of two values
+5.3k Android Studio : Import third-party library or package into Gradle Scripts