Search⌘ K
AI Features

Solution: Basic Go Data Types

Learn how to concatenate arrays and slices in Go through practical examples. Understand the difference between fixed-length arrays and slices, how to combine them efficiently, and the implications of passing arrays by value.

Problem 1: Solution

Here is an example of a function in Go that takes two arrays as input and concatenates them into a new slice:

Go (1.19.0)
package main
import (
"fmt"
)
func concatenate(a1 [3]int, a2 [3]int) []int {
var s []int
var a3 [6]int
for i := 0; i < len(a1); i++ {
a3[i] = a1[i]
}
for i := 0; i < len(a2); i++ {
a3[i + len(a1)] = a2[i]
}
s = a3[0:6] //creates a slice from a3[0] to a3[5]
return s
}
func main() {
arr1 := [3]int{1, 2, 3}
arr2 := [3]int{4, 5, 6}
newSlice := concatenate(arr1, arr2)
fmt.Println(newSlice)
}

Code explanation

  • Lines 9–14: The concatenate() function takes in two arrays of integers, a1 and a2, and creates a new array, a3, with a length equal to the sum of the lengths of a1 and a2. The function then iterates through the elements of both a1 and a2 and assigns them to the corresponding positions in a3 ...