Menu
CoddyTech

重新切片

Coddy Go 中的切片和映射 课程的第 6 课,共 21 课。

Go 提供了一种叫作重新切片的功能,也就是对子切片再次进行切片。我们来看一个例子,了解它的用法:

s := []string{"games", "coffee", "code", "play", "walk", "read", "learn"}

这里,我们定义了一个包含 7 个元素的切片。接下来对它进行切片,从 7 个元素中只取前 4 个:

s := []string{"games", "coffee", "code", "play", "walk", "read", "learn"}
newS := s[0:4]
fmt.Println(newS)

这会返回一个包含 4 个元素的切片:

[games coffee code play]

重新切片是指对 newS 切片再次进行切片,就像这样:

s := []string{"games", "coffee", "code", "play", "walk", "read", "learn"}
newS := s[0:4]
fmt.Println("Slicing: ", newS)
newS2 := newS[2:]
fmt.Println("Reslicing: ", newS2)

这样我们会得到:

Slicing:  [games coffee code play]
Reslicing:  [code play]

请注意,切片后,我们可以通过索引访问切片中的元素。例如:

s := []string{"games", "coffee", "code", "play", "walk", "read", "learn"}
newS := s[0:4]
fmt.Println("Slicing: ", newS)
fmt.Println(newS[2])

在这个例子中,我们获取了索引为 2 的元素:

Slicing:  [games coffee code play]
code

同样,我们也可以修改值:

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])

输出应该是:

Slicing:  [games coffee code play]
Before Modification : code
After Modification : sleep

同样,我们也可以向切片中添加元素:

newS := s[0:4]
fmt.Println("Slicing: ", newS)
newS = append(newS, "sleep")
fmt.Println("After Modification :", newS)

结果会是:

Slicing:  [games coffee code play]
After Modification : [games coffee code play sleep]
challenge icon

挑战

简单

在提供的代码中,我们定义了一个字符串类型的切片。

  • 创建另一个名为“fruits”的切片,并将给定切片的最后五个元素存入其中。
  • 在屏幕上打印“fruits”切片。
  • 向“fruits”切片添加两个元素:<strong>"pear"</strong> 和 <strong>"pineapple"</strong>。
  • 打印更新后的“fruits”切片。

亲手试试

package main

import "fmt"

func main() {
    // 定义切片
	str:= []string{"apple", "banana", "cherry", "date", "fig", "grape", "kiwi", "lemon", "mango"}
	// 获取最后 5 个元素
	 
	// 将切片打印到屏幕上
 
	// 向切片添加两个元素
 
	// 打印更新后的切片
 

}

Go 中的切片和映射中的所有课

自己练习: Go 在线编译器