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
+9k Golang : Handle sub domain with Gin
+8.8k Golang : Find network service name from given port and protocol
+6.3k Golang : Selection sort example
+5.6k Swift : Get substring with rangeOfString() function example
+9.4k Facebook : Getting the friends list with PHP return JSON format
+16.4k Golang : Check if a string contains multiple sub-strings in []string?
+35.2k Golang : Smarter Error Handling with strings.Contains()
+22.1k Golang : Repeat a character by multiple of x factor
+6.7k Golang : Output or print out JSON stream/encoded data
+21.4k Golang : How to read float value from standard input ?
+10.4k Swift : Convert (cast) String to Integer