Sling Academy
Home/Golang/Building Custom Types with Arrays in Go

Building Custom Types with Arrays in Go

Last updated: November 23, 2024

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.

Next Article: Preventing Index Out-of-Bounds Errors in Go Arrays

Previous Article: Efficiently Copying Arrays in Go

Series: Working with Arrays in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant