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
+30.6k Golang : Validate email address with regular expression
+11k Golang : How to parse plain email text and process email header?
+8k Golang : Go as a script or running go with shebang/hashbang style
+4.5k Golang : Stop goroutine without channel
+15.6k Golang : Get input from keyboard
+12.9k Golang : Get uploaded file name or access uploaded files
+25.1k Golang : Calculate future date with time.Add() function
+8.9k Golang : Setting variable value with ldflags
+3.5k Golang : Valued expressions and functions example
+7.4k Golang : Implementing class(object-oriented programming style)
+26.8k Golang : Read, Write(Create) and Delete Cookie example
+5.9k Golang : constant 20013 overflows byte error message