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
+9.5k PHP : Get coordinates latitude/longitude from string
+11.9k Golang : convert(cast) string to integer value
+13.8k Golang : Google Drive API upload and rename example
+9k Golang : How to check if a string with spaces in between is numeric?
+26k Golang : Get executable name behind process ID example
+10.6k Golang : Removes punctuation or defined delimiter from the user's input
+9k Golang : Apply Histogram Equalization to color images
+26.5k Golang : Convert file content into array of bytes
+22.3k Golang : Set and Get HTTP request headers example
+8.7k Golang : Sort lines of text example
+20.5k Golang : Underscore or snake_case to camel case example
+23.4k Find and replace a character in a string in Go