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
+8k Golang : HTTP Server Example
+7.7k Golang : Get today's weekday name and calculate target day distance example
+13.7k Golang : Gin framework accept query string by post request example
+5.8k Unix/Linux : How to open tar.gz file ?
+8.4k Golang : Another camera capture GUI application with GTK and OpenCV
+5.7k Golang : Find change in a combination of coins example
+4.6k JavaScript: Add marker function on Google Map
+9.5k Golang : Eroding and dilating image with OpenCV example
+6k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+5.6k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+36.3k Golang : Validate IP address
+14.7k Golang : How to check for empty array string or string?