Reslicing
Lesson 6 of 21 in Coddy's Slices and Maps in Golang course.
Go offers something called reslicing, which means performing another slicing for the subslice. Let's take an example to understand this correctly:
s := []string{"games", "coffee", "code", "play", "walk", "read", "learn"}Here, we define a slice with 7 elements. Let's slice this and get just the first 4 elements out of 7:
s := []string{"games", "coffee", "code", "play", "walk", "read", "learn"}
newS := s[0:4]
fmt.Println(newS)This will return a slice of 4 elements:
[games coffee code play]Reslicing is the ability to perform another slicing for our newS slice just like this:
s := []string{"games", "coffee", "code", "play", "walk", "read", "learn"}
newS := s[0:4]
fmt.Println("Slicing: ", newS)
newS2 := newS[2:]
fmt.Println("Reslicing: ", newS2)And we will get:
Slicing: [games coffee code play]
Reslicing: [code play]Note that when we perform slicing, we can access the elements of the slice by index. For example:
s := []string{"games", "coffee", "code", "play", "walk", "read", "learn"}
newS := s[0:4]
fmt.Println("Slicing: ", newS)
fmt.Println(newS[2])Here in this example, we get the element at index 2:
Slicing: [games coffee code play]
codeIn the same way, we can modify the value:
s := []string{"games", "coffee", "code", "play", "walk", "read", "learn"}
newS := s[0:4]
fmt.Println("Slicing: ", newS)
fmt.Println("Before Modification :", newS[2])
newS[2] = "sleep"
fmt.Println("After Modification :", newS[2])And the output should be:
Slicing: [games coffee code play]
Before Modification : code
After Modification : sleepAlso, in the same way, we can add elements to the slice:
newS := s[0:4]
fmt.Println("Slicing: ", newS)
newS = append(newS, "sleep")
fmt.Println("After Modification :", newS)And the result will be:
Slicing: [games coffee code play]
After Modification : [games coffee code play sleep]Challenge
EasyIn the provided code, we define a slice of type string.
- Create another slice called "fruits" and store in it the last five elements of the given slice.
- Print the "fruits" slice to the screen.
- Add two elements to the "fruits" slice:
<strong>"pear"</strong>and<strong>"pineapple"</strong>. - Print the updated "fruits" slice.
Try it yourself
package main
import "fmt"
func main() {
// Define Slice
str:= []string{"apple", "banana", "cherry", "date", "fig", "grape", "kiwi", "lemon", "mango"}
// Get the last 5 element
// Print the Slice to the screen
// Add two element to the slice
// print the updated slice
}All lessons in Slices and Maps in Golang
1Introduction
Introduction