Arrays in Go

Arrays in Go are fixed-size collections of elements of the same type. They are declared using square brackets and a length.

Creating Arrays

To create an array, you specify the type of elements and the length of the array:

Go

var numbers [5]int

This creates an array of 5 integers.

Accessing Elements

You can access individual elements of an array using their index, which starts from 0:

Go

numbers[0] = 10
numbers[1] = 20

fmt.Println(numbers[0]) // Output: 10

Array Length

The length of an array is determined at compile time and cannot be changed. You can access the length of an array using the len function:

Go

length := len(numbers)
fmt.Println(length) // Output: 5

Array Initialization

You can initialize an array with values when you declare it:

Go

fruits := [3]string{"apple", "banana", "orange"}

Arrays and gRPC

Arrays can be used in gRPC services to represent collections of data. For example, you might use an array to represent a list of items in a response message.

Example:

Protocol Buffers

message Item {
  string name = 1;
  int32 quantity = 2;
}

message Order {
  repeated Item items = 1;
}

Go

type orderServer struct{}

func (s *orderServer) GetOrder(ctx context.Context, in *pb.OrderRequest) (*pb.Order, error) {
  items := []*pb.Item{
    {Name: "apple", Quantity: 2},
    {Name: "banana", Quantity: 3},
  }
  return &pb.Order{Items: items}, nil
}

Limitations of Arrays

While arrays are useful for fixed-size collections, they have some limitations:

  • Fixed size: The size of an array cannot be changed after it is created.
  • Inefficient for dynamic data: If you need to add or remove elements from a collection, arrays can be inefficient.

Slices: A More Flexible Alternative

To overcome the limitations of arrays, Go provides slices, which are dynamic-length sequences of elements. Slices are backed by arrays but offer more flexibility in terms of size and operations.

Go Modules
Understand Slices in Go

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?