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
+14.5k Golang : How to check for empty array string or string?
+8.3k Golang : Another camera capture GUI application with GTK and OpenCV
+37k Upload multiple files with Go
+8.1k Golang : Implementing class(object-oriented programming style)
+9.8k Golang : Use regular expression to get all upper case or lower case characters example
+40.7k Golang : How to count duplicate items in slice/array?
+13.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+5.8k Golang : Compound interest over time example
+12.2k Golang : Forwarding a local port to a remote server example
+6.4k Golang : Check if password length meet the requirement
+7.3k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+8.1k Your page has meta tags in the body instead of the head