Golang : Combine slices but preserve order example
In the previous tutorial on how to join arrays in Golang, we use the append
function to join arrays/slices. However, there are times when we need to pack or join few arrays/slices into a single array, but preserving their order and to transmit the single array over the network or serialized to disk before unpacking the single array back into the original arrays later on.
To use append
function for this situation is unwise. Below is a simple example on how to pack the arrays/slices into a single 2-dimensional array and unpack it.
package main
import (
"fmt"
)
func main() {
a := []int{1, 2, 3}
b := []int{4, 5, 6}
c := []int{7, 8, 9}
d := [][]int{a, b}
// two slices in one slice
fmt.Println(d)
// two distinct slices
fmt.Println(a, b)
// to add c, need to use new variable e
e := [][]int{a, b, c}
fmt.Println(e)
// change order just for fun
f := [][]int{c, b, a}
fmt.Println(f)
// unpack
fmt.Println("c : ", f[0])
fmt.Println("b : ", f[1])
fmt.Println("a : ", f[2])
}
Output:
[[1 2 3] [4 5 6]]
[1 2 3] [4 5 6]
[[1 2 3] [4 5 6] [7 8 9]]
[[7 8 9] [4 5 6] [1 2 3]]
c : [7 8 9]
b : [4 5 6]
a : [1 2 3]
Happy coding!
See also : Golang : Join arrays or slices 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
+10.6k PHP : Convert(cast) bigInt to string
+8.1k Golang : Implementing class(object-oriented programming style)
+10.8k Golang : Create S3 bucket with official aws-sdk-go package
+10.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+13.8k Golang : Simple word wrap or line breaking example
+28.3k Golang : Detect (OS) Operating System
+16.2k Golang : How to implement two-factor authentication?
+9.1k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+25.4k Golang : How to write CSV data to file
+8.5k Golang : Accept any number of function arguments with three dots(...)
+12k Golang : Validate email address
+5.2k How to check with curl if my website or the asset is gzipped ?