Go Program to Create and Initialize a Slice

Introduction

A slice in Go is a dynamically-sized, flexible view into the elements of an array. Unlike arrays, slices can grow and shrink as needed. This guide will demonstrate how to create and initialize a slice in Go.

Problem Statement

Create a Go program that:

  • Declares and initializes a slice.
  • Displays the elements of the slice.

Example:

  • Input: []int{1, 2, 3, 4, 5}
  • Output: Slice: [1 2 3 4 5]

Solution Steps

  1. Import the fmt Package: Use import "fmt" for formatted I/O operations.
  2. Write the Main Function: Define the main function, which is the entry point of every Go program.
  3. Create and Initialize the Slice: Use different methods to create and initialize a slice.
  4. Display the Slice: Use fmt.Println to display the elements of the slice.

Go Program

package main

import "fmt"

/**
 * Go Program to Create and Initialize a Slice
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 1: Create and initialize a slice using a slice literal
    slice1 := []int{1, 2, 3, 4, 5}
    fmt.Println("Slice 1:", slice1)

    // Step 2: Create and initialize a slice using the make function
    slice2 := make([]int, 5)
    slice2[0] = 10
    slice2[1] = 20
    slice2[2] = 30
    slice2[3] = 40
    slice2[4] = 50
    fmt.Println("Slice 2:", slice2)

    // Step 3: Create a slice from an array
    array := [5]int{100, 200, 300, 400, 500}
    slice3 := array[1:4] // Slicing the array from index 1 to 3
    fmt.Println("Slice 3:", slice3)
}

Explanation

Step 1: Create and Initialize a Slice Using a Slice Literal

  • A slice can be created and initialized directly using a slice literal. For example, slice1 := []int{1, 2, 3, 4, 5} creates a slice of integers with five elements.

Step 2: Create and Initialize a Slice Using the make Function

  • The make function can be used to create a slice with a specified length. For example, slice2 := make([]int, 5) creates a slice of integers with a length of 5, initialized with zero values. The elements can then be individually assigned.

Step 3: Create a Slice from an Array

  • A slice can also be created from an existing array. For example, slice3 := array[1:4] creates a slice from the array, including elements from index 1 to 3.

Step 4: Display the Slices

  • The program prints the slices using fmt.Println to display their elements.

Output Example

Example 1:

Slice 1: [1 2 3 4 5]
Slice 2: [10 20 30 40 50]
Slice 3: [200 300 400]

Conclusion

This Go program demonstrates different ways to create and initialize a slice, including using a slice literal, the make function, and creating a slice from an array. It covers basic programming concepts such as slice manipulation, array slicing, and initialization in Go. This example is useful for beginners learning Go programming and understanding how to work with slices.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top