Arrays in Go are a versatile and foundational component when constructing custom types. While Go emphasizes simplicity and efficiency, its array handling allows for the development of powerful custom data structures. This guide will walk you through building custom types with arrays, ranging from basic concepts to more advanced implementations.

Basic: Understanding Arrays in Go

Before we create custom types, let’s understand Go’s arrays. An array is a fixed-size sequence of elements with the same type, laid out sequentially in memory.

package main

import "fmt"

func main() {
    // Declare an array of integers with 5 elements
    var numbers [5]int

    // Assign values to the array
    numbers[0] = 1
    numbers[1] = 2
    fmt.Println(numbers)

    // Initialize an array with values
    fruits := [3]string{"Apple", "Banana", "Cherry"}
    fmt.Println(fruits)
}

In this snippet, and arrays are declared and used with both integer and string types.

Intermediate: Creating Custom Types with Type Aliases

Using arrays we can define new types. Type aliases allow a new, distinct type rather than just a redefined variable's original type.

package main

import "fmt"

type Weekdays [7]string

func main() {
    var week Weekdays = [7]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
    fmt.Println(week)
}

This example defines a new type, Weekdays, as an array of strings with a fixed length of 7. This is beneficial for readability and code clarity, allowing arrays to take on more meaningful uses.

Advanced: Custom Methods on Array-based Types

In Go, it’s possible to attach methods to struct and type, including our custom array-based types. This enables object-like manipulation of arrays.

package main

import "fmt"

type Scores [5]int

func (s Scores) Average() float64 {
    var sum int
    for _, score := range s {
        sum += score
    }
    return float64(sum) / float64(len(s))
}

func main() {
    scores := Scores{80, 75, 90, 85, 100}
    fmt.Println("Scores:", scores)
    fmt.Printf("Average: %.2f\n", scores.Average())
}

In this advanced example, a new type Scores is defined, and we attach a method Average which calculates the average of the numbers contained within the Scores array.

With arrays and custom types, Go can handle much more sophisticated data structures while maintaining simplicity and performance. Understanding these basic to advanced techniques is key to leveraging Go's strengths in your applications.