How to Concatenate Multiple Slices in Go

1. Introduction

In Go, concatenating slices is a process of joining two or more slices into one. This can be useful when you need to combine data from different sources or simply merge collections. Go's built-in append function simplifies this task. This blog post will show how to concatenate multiple slices in Go.

Definition

Concatenation of slices in Go involves creating a new slice and appending each slice to it sequentially using the append function. This function is variadic, so it can accept multiple values to append to a slice.

2. Program Steps

1. Define and initialize the slices you want to concatenate.

2. Use the append function to concatenate the slices.

3. Print the resulting concatenated slice.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Define and initialize the slices
	sliceA := []string{"apple", "orange"}
	sliceB := []string{"banana", "grape"}
	sliceC := []string{"lemon", "peach"}

	// Step 2: Use append to concatenate the slices
	// Start with an empty slice of the same type, or use one of the existing slices.
	combinedSlice := append(sliceA, sliceB...)
	combinedSlice = append(combinedSlice, sliceC...)

	// Step 3: Print the resulting concatenated slice
	fmt.Println("Combined Slice:", combinedSlice)
}

Output:

Combined Slice: [apple orange banana grape lemon peach]

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - The Format package is imported for output functionality.

3. sliceA, sliceB, and sliceC are initialized with some fruit names to serve as example data for concatenation.

4. The append function is used to concatenate sliceB and sliceC to sliceA. The ... operator is used to expand slices within the append function call.

5. The combinedSlice is declared by concatenating sliceA with sliceB, then appending sliceC to the result.

6. The fmt.Println function is called to print the combined slice.

7. The output confirms the concatenation, showing a single slice containing all the elements from the three original slices.


Comments