This blog is primarily focus on Java fundamentals and the libraries built on top of Java programming language. Most of the post are example oriented, hope you have fun in reading my blog....:)
Showing posts with label go pass by reference. Show all posts
Showing posts with label go pass by reference. Show all posts
Friday, 3 May 2019
Thursday, 2 May 2019
Go language: Slices are passed by reference
In Go
language, Arrays are passed by value, whereas slices are passed by reference.
func
updateCountries(countries []string) {
countries[0] = "Dummy"
countries[1] = "Dummy"
countries[2] = "Dummy"
countries[3] = "Dummy"
countries[4] = "Dummy"
}
For
example, if you call updateCountries method by passing a slice as an argument,
the changes done for the slice ‘countries’ inside the method ‘updateCountries’
will be reflected outside.
App.go
package main import "fmt" func main() { countries := []string{} countries = append(countries, "India") countries = append(countries, "Bangladesh") countries = append(countries, "Canada") countries = append(countries, "Austria") countries = append(countries, "Germany") fmt.Println(countries) fmt.Println("\nUpdating countries with Dummy data") updateCountries(countries) fmt.Println() fmt.Println(countries) } func updateCountries(countries []string) { countries[0] = "Dummy" countries[1] = "Dummy" countries[2] = "Dummy" countries[3] = "Dummy" countries[4] = "Dummy" }
Output
[India
Bangladesh Canada Austria Germany]
Updating
countries with Dummy data
[Dummy
Dummy Dummy Dummy Dummy]
Subscribe to:
Posts (Atom)