Skip to content

Latest commit

 

History

History
138 lines (94 loc) · 3.03 KB

File metadata and controls

138 lines (94 loc) · 3.03 KB

15) Slices

Linkedin Follow X Follow
Interactive Learning


Slices

A slice is like an array, but its size can grow and shrink.

Slices are used much more often than arrays in Go.

  Array: [3]string — fixed size, cannot grow

  +--------+--------+----------+
  |"Berlin"| "Tokyo"|"Istanbul"|
  +--------+--------+----------+
    [0]       [1]       [2]       len = 3 (always 3)


  Slice: []string — can grow with append()

  +--------+--------+----------+---+---
  |"Berlin"| "Tokyo"|"Istanbul"|   | ...
  +--------+--------+----------+---+---
    [0]       [1]       [2]       len = 3, but can grow

How to Declare a Slice

↳ 1) Declare with Values

No size inside the brackets:

colors := []string{"red", "green", "blue"}

Notice the difference from arrays: []string instead of [3]string.

↳ 2) Declare an Empty Slice

var colors []string

This creates an empty slice with length 0.

Slices Operations

↳ 1) Access Elements by Index

Same as arrays:

fmt.Println(colors[0]) // red

↳ 2) Add Elements with append()

Use append() to add elements to a slice:

colors := []string{"red", "green"}
colors = append(colors, "blue")

append() returns a new slice with the added element. You must assign it back.

↳ 3) Get the Length

Use len():

fmt.Println(len(colors)) // 3

↳ 4) Slice a Slice

You can create a sub-slice using the [start:end] syntax:

colors := []string{"red", "green", "blue", "yellow"}
subset := colors[1:3]
fmt.Println(subset) // [green blue]

colors[1:3] takes elements from index 1 up to (but not including) index 3.

Example Code

There are some slice operations in main.go file.

But they are incomplete.

Fix the Code

Open main.go file and complete the code lines.

Then validate your code by running:

go run topic.go 15 validate

✅ If everything is ok, you should see:

OK!

Conclusion

Now you know how to use slices in Go.

Continue to the next topic 👇

Maps ⮕️