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
+22.5k Golang : Convert Unix timestamp to UTC timestamp
+11k Golang : Replace a parameter's value inside a configuration file example
+11.6k CodeIgniter : Import Linkedin data
+25.6k Golang : convert rune to integer value
+12.4k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+27.6k Golang : dial tcp: too many colons in address
+9.5k Android Studio : Indicate progression with ProgressBar example
+21.8k Golang : How to reverse slice or array elements order
+19.9k Golang : Append content to a file
+13.1k Golang : Calculate elapsed years or months since a date
+19.9k Golang : How to get time from unix nano example
+8.3k Golang : Number guessing game with user input verification example