Menu
Coddy logo textTech

Slices vs Arrays

Lesson 2 of 21 in Coddy's Slices and Maps in Golang course.

In other programming languages, we often encounter dynamic arrays. In Go, these are referred to as slices, allowing us to dynamically add or remove elements. However, it's important to note that a slice itself doesn't store elements; rather, it serves as a window to an array.

Now, let's explore the difference between a slice and an array through an example. Consider an array with three elements:

arr := [3]string{"Python", "Go", "Rust"}

As we know, an array is a fixed collection type, making it impossible to add elements. If we attempt to add a new element, errors will arise.

Here's where slices come in to address this limitation. Let's understand this with an example:

var books = []string{"SQL", "Java", "C++"}

As you can see, we define the slice <strong>books</strong> the same way as a regular array, with the only difference being that we don't define the length.

This allows us to add or remove elements dynamically during runtime an operation impossible with arrays.

Accessing elements in a slice is similar to arrays, utilizing indices:

fmt.Println(books[1]) // Java

In Go, slices offer flexibility for working with collections by allowing dynamic changes, unlike arrays which have a fixed structure.

challenge icon

Challenge

Easy
  • Define a slice with the following elements: "Learn Go", "Learn Python", "Learn Java", "Coddy.tech" sequentially.
  • Print "Learn Go" and "Coddy.tech" to the screen using indexes.
  • You can name the slice as you prefer.

 

Try it yourself

package main

import (
	"fmt"
)

func main() {
    // Your Code Here
    
}

All lessons in Slices and Maps in Golang