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
+8.6k Your page has meta tags in the body instead of the head
+21.7k Curl usage examples with Golang
+36.9k Golang : Display float in 2 decimal points and rounding up or down
+11k Golang : Command line file upload program to server example
+9.4k Golang : How to capture return values from goroutines?
+9.1k Golang : Populate or initialize struct with values example
+11.7k Use systeminfo to find out installed Windows Hotfix(s) or updates
+7.8k Golang : get the current working directory of a running program
+11k Golang : Sieve of Eratosthenes algorithm
+8.8k Golang : Progress bar with ∎ character
+7.4k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+16.7k Golang : Execute terminal command to remote machine example