Golang : Join arrays or slices example
A quick note on how to join arrays or slices in Golang. So used to Python way of joining arrays with +
symbol. However, it is not available in Golang :(
To join two arrays in Golang, use the append
function instead.
package main
import (
"fmt"
)
func main() {
list1 := []int{1, 2, 3}
list2 := []int{4, 5, 6}
// python way - will not work in Golang
//list3 := list1 + list2
//fmt.Println(list3)
list3 := list1
// example
// to combine two slices or join arrays, use for loop and builtin append function
for index, _ := range list2 {
list3 = append(list3, list2[index])
}
fmt.Println(list3)
// another example
// super quick way to join arrays
fmt.Println(append(list1, list2...))
}
Output:
[1 2 3 4 5 6]
[1 2 3 4 5 6]
See also : Golang : Combine slices of complex numbers and operation example
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
+6.3k Elasticsearch : Shutdown a local node
+4.9k Golang : Print instead of building pyramids
+6.2k Golang : Calculate diameter, circumference, area, sphere surface and volume
+12.8k Golang : List objects in AWS S3 bucket
+19.5k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+16.1k Golang : Check if a string contains multiple sub-strings in []string?
+23.7k Golang : Call function from another package
+4.6k HTTP common errors and their meaning explained
+9.4k Golang : Format strings to SEO friendly URL example
+11.1k Golang : Concatenate (combine) buffer data example
+11.1k Golang : Post data with url.Values{}
+17.6k Golang : How to log each HTTP request to your web server?