Go Example: Slices

1. Introduction

Slices are a key data type in Go, providing a more powerful interface to sequences compared with arrays. Unlike arrays, slices are flexible and can be resized. They are built on top of arrays to provide greater power and utility. This blog post will walk through various slice operations in Go.

2. Program Steps

1. Create a slice.

2. Append elements to a slice.

3. Copy one slice to another.

4. Iterate over a slice using a range-based loop.

5. Slice a slice to make a new slice.

6. Create a slice using the make function.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Create a slice
	s := make([]string, 3)
	fmt.Println("emp:", s)

	// Step 2: Append elements to a slice
	s = append(s, "d")
	s = append(s, "e", "f")
	fmt.Println("apd:", s)

	// Step 3: Copy one slice to another
	c := make([]string, len(s))
	copy(c, s)
	fmt.Println("cpy:", c)

	// Step 4: Iterate over a slice
	for i, v := range s {
		fmt.Printf("%d: %s\n", i, v)
	}

	// Step 5: Slice a slice
	l := s[2:5]
	fmt.Println("sl1:", l)

	// Step 6: Create a slice using the make function
	t := make([]string, len(s))
	copy(t, s)
	fmt.Println("make:", t)
}

Output:

emp: [  ]
apd: [  d e f]
cpy: [  d e f]
0:
1:
2: d
3: e
4: f
sl1: [d e f]
make: [  d e f]

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package, which provides formatted I/O.

3. make([]string, 3) is used to create a slice s with an initial length of three.

4. append is used to add elements to slice s. It automatically resizes the slice as needed.

5. copy is used to copy elements from slice s to slice c. Both slices must exist before copying.

6. A for loop with range iterates over slice s, printing each index and its corresponding value.

7. Slicing syntax s[2:5] is demonstrated, creating a new slice l from s that includes elements from index 2 to 4.

8. make is used again to create another slice t with the same length as s, followed by a copy from s to t.

9. The output shows each step's results: creating a slice, appending elements, copying slices, iterating over a slice, and slicing a slice.


Comments