Go (Golang) / Go Data Structures

Working with Arrays and Slices in Go

In this tutorial, we will dig deep into how arrays and slices work in Go. We'll cover how to declare, initialize and manipulate these fundamental data structures.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers essential data structures in Go, including arrays, slices, and maps.

Introduction

Welcome to this tutorial! Our main focus here will be to understand and work with Arrays and Slices in Go.

By the end of this tutorial, you will learn:
- How to declare and initialize arrays and slices in Go
- How to manipulate these data structures
- Best practices related to arrays and slices

Prerequisites: Basic understanding of Go programming language.

Step-by-Step Guide

In Go, both arrays and slices are used to store multiple values of the same data type. However, they work differently:

  • Array is a fixed-length sequence of items of the same type. Once you declare the size of an array, it cannot be resized.

  • Slice is a dynamic-length sequence of items of the same type. Slices are more flexible and commonly used than arrays in Go.

Declaring and Initializing Arrays

To declare an array, you specify the type of its elements and the number of items it will hold. Here's the general syntax:

var arrayName [size]Type

To initialize an array while declaring it, you can use the following syntax:

arrayName := [size]Type{element1, element2, ..., elementN}

Declaring and Initializing Slices

A slice does not require you to specify its size during declaration. Here's how you can declare a slice:

var sliceName []Type

To initialize a slice, you can use the built-in make function:

sliceName := make([]Type, size)

Manipulating Arrays and Slices

Arrays in Go are value types. That means when you assign an array to a new variable or pass it to a function, the entire array is copied.

Slices, on the other hand, are reference types. When you assign a slice to a new variable or pass it to a function, only the reference to the underlying array is copied.

Code Examples

Let's see some practical examples of using arrays and slices in Go.

  1. Declaring and initializing an array:
// Declare and initialize an array
numbers := [5]int{10, 20, 30, 40, 50}

// Print the array
fmt.Println(numbers)

This will output:

[10 20 30 40 50]
  1. Declaring and initializing a slice:
// Declare and initialize a slice
numbers := make([]int, 5)

// Fill the slice with values
numbers = []int{10, 20, 30, 40, 50}

// Print the slice
fmt.Println(numbers)

This will output:

[10 20 30 40 50]

Summary

In this tutorial, we've learned about arrays and slices in Go. We've covered how to declare, initialize, and manipulate these data structures.

Next, you might want to learn about other data structures in Go, such as maps and structs. You can also explore how to work with multidimensional arrays and slices.

Practice Exercises

Here are some exercises for you to practice:

  1. Write a program that declares an array of integers and prints it.

  2. Write a program that declares a slice of strings, adds three names to it, and prints it.

  3. Write a program that takes an array and returns a slice containing only the elements at even indices.

Solutions

  1. An array of integers:
// Declare and initialize an array
numbers := [5]int{10, 20, 30, 40, 50}

// Print the array
fmt.Println(numbers)
  1. A slice of strings:
// Declare and initialize a slice
names := make([]string, 0)

// Add names to the slice
names = append(names, "John", "Jane", "Joe")

// Print the slice
fmt.Println(names)
  1. A function that returns a slice of even-index elements from an array:
func evenIndices(array [6]int) []int {
    slice := make([]int, 0)

    for i := 0; i < len(array); i += 2 {
        slice = append(slice, array[i])
    }

    return slice
}

// Test the function
numbers := [6]int{10, 20, 30, 40, 50, 60}
fmt.Println(evenIndices(numbers))

This should output [10 30 50], which are the elements at the 0th, 2nd, and 4th indices of the array.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help