Slicing
Lesson 4 of 21 in Coddy's Slices and Maps in Golang course.
Let's delve into the concept of slicing and discuss the slice expression. Slicing means taking an original array or slice and narrowing it down. To better understand this, let's go through some examples.
Suppose we have a slice like this in Go:
arr := []string{"code", "coffee", "tea", "water"}Now, let's say we are only interested in getting "code" and "coffee" from this slice. We can achieve this through slicing, as shown below:
newArr := arr[0:2]The syntax for slicing is as follows: <strong>arr[start:stop]</strong>. We specify the name of the slice or array that we want to shrink, and within square brackets, we provide the starting position, followed by a colon, and then the ending position.
The starting position should be an index of an element within the slice, starting from zero.
The ending position indicates the position of the element, not the index, so it starts from 1.
In our example, we start from index 0 and retrieve 2 elements, expressed as <strong>arr[0:2]</strong>. If the starting position is 0, it can be omitted, resulting in the same outcome:
arr[:2]This retrieves the elements "code" and "coffee" from the slice.
We can start and end slicing as desired. For example, if we want to get "coffee" and "tea" from the slice, we can do it like this:
arr := []string{"code", "coffee", "tea", "water"}
newArr := arr[1:3]
Challenge
EasyIn the given code, we define a slice of 6 elements of type string. Use slicing to retrieve the values <strong>"apple"</strong> ,<strong>"orange"</strong> and <strong>"banana"</strong> from the original slice and print them to the screen.
Try it yourself
package main
import "fmt"
func main() {
// fruits Slice Don't change this!
fruits := []string{"pineapple", "kiwi", "apple", "orange", "banana", "grape", "kiwi"}
// Slicing the fruits slice
// Print the slice to the screen
}All lessons in Slices and Maps in Golang
1Introduction
Introduction