Menu
Coddy logo textTech

Slicing Ways

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

In the previous lessons, we discussed the fundamentals of slicing and how it can be utilized to reduce the size of a slice or an array. We mentioned that the syntax for slicing is <strong>name[start:stop]</strong>. Let's explore various ways we can use this slicing expression.

For instance, consider the following expression:

arr := []string{"kiwi", "apple", "orange", "banana", "grape", "pineapple"}
newArr := arr[:4]

This indicates that we want to start from index 0 and go up to the 4th element:

[kiwi apple orange banana]

For example, if you see an expression like this:

arr := []string{"kiwi", "apple", "orange", "banana", "grape", "pineapple"}
newArr := arr[4:]

This means we are starting from index 4 to the end of the slice:

[grape pineapple]

If you see an expression like this:

arr := []string{"kiwi", "apple", "orange", "banana", "grape", "pineapple"}
newArr := arr[:]

This means we are starting from index 0 to the end of the slice (creating a copy of our original slice):

[kiwi apple orange banana grape pineapple]

Note that when we perform slicing, we should pay attention to the length of the original slice. We can't use a position that is not included in the slice, for example:

arr := []string{"kiwi", "apple", "orange", "banana", "grape", "pineapple"}
newArr := arr[:8]

This will result in an error, as the position 8 is outside our slice capacity, and we only have 7 elements in our slice.

challenge icon

Challenge

Easy

In the given code, we define a slice of 8 elements. We need to get the whole slice except for the first and the last elements. Print the result to the screen.

Try it yourself

package main

import "fmt"

func main() {
    // Define a Slice
	languages := []string{"C", "C++", "Java", "Python", "JavaScript", "Ruby", "Go", "Swift"}
    // Slicing
	 
    // Print the slice to the screen
	 

}

All lessons in Slices and Maps in Golang