Go 切片

Slice 是一种包含相似数据类型的集合,就像数组一样。

然而,与数组不同的是,slice 没有固定的大小。我们可以从数组中添加或删除元素。

在 Golang 中创建 Slice

以下是在 Golang 中创建 slice 的方法

numbers := []int{1, 2, 3, 4, 5}

这里,

  • numbers - slice 的名称
  • int - 表示 slice 只包含整数
  • {1, 2, 3, 4, 5} - slice 的元素

您可能已经注意到,我们留空了 [] 符号。这是因为我们可以向 slice 添加元素,这将改变其大小。

注意:如果我们为 [] 符号提供大小,它将变成一个数组。例如,

// this is an array
numbers := [5]int{1, 2, 3, 4, 5}

// this is a slice
numbers := []int{1, 2, 3, 4, 5}

Golang Slice 示例

// Program to create a slice and print its elements

package main
import "fmt"

func main() {

  // declare slice variable of type integer
  numbers := []int{1, 2, 3, 4, 5}

  // print the slice
  fmt.Println("Numbers: ", numbers)
}

输出

Numbers: [1 2 3 4 5]

在上面的示例中,我们创建了一个名为 numbers 的 slice。在这里,int 指定 numbers slice 只能存储整数。

注意:我们也可以使用 var 关键字来创建 slice。例如,

var numbers = []int{1, 2, 3, 4}

从 Golang 数组创建 Slice

在 Go 编程中,我们也可以从现有数组创建 slice。例如,

假设我们有一个数字数组

numbers := [8]int{10, 20, 30, 40, 50, 60, 70, 80}

现在,我们可以从这个数组中切片指定的元素来创建一个新的 slice。

sliceNumbers = numbers[4, 7]

这里,

  • 4 是我们从中切片数组元素的起始索引
  • 7 是我们想要获取数组元素结束的索引

从数组创建 slice 时,起始索引是包含在内的,而结束索引是不包含在内的。因此,我们的 slice 将包含元素 [50, 60, 70]


示例:在 Go 中从数组创建 Slice

// Program to create a slice from an array

package main
import "fmt"

func main() {

  // an integer array
  numbers := [8]int{10, 20, 30, 40, 50, 60, 70, 80}

// create slice from an array sliceNumbers := numbers[4 : 7]
fmt.Println(sliceNumbers) }

输出

[50, 60, 70]

Slice 函数

在 Go 中,slice 提供了各种内置函数,允许我们对 slice 执行不同的操作。

函数 描述
append() 向 slice 添加元素
copy() 将一个 slice 的元素复制到另一个 slice
Equal() 比较两个 slice
len() 查找 slice 的长度

向 Slice 添加元素

我们使用 append() 函数向 slice 添加元素。例如,

// Program to add elements to a slice

package main
import "fmt"

func main() {
  primeNumbers := []int{2, 3}
  
// add elements 5, 7 to the slice primeNumbers = append(primeNumbers, 5, 7)
fmt.Println("Prime Numbers:", primeNumbers) }

输出

Prime Numbers: [2 3 5 7]

在这里,代码

primeNumbers = append(primeNumbers, 5, 7)

将元素 57 添加到 primeNumbers

我们也可以使用 append() 函数将一个 slice 的所有元素添加到另一个 slice。例如,

// Program to add elements of one slice to another

package main
import "fmt"

func main() {
  
  // create two slices
  evenNumbers := []int{2, 4}
  oddNumbers := []int{1, 3}  
  
// add elements of oddNumbers to evenNumbers evenNumbers = append(evenNumbers, oddNumbers...)
fmt.Println("Numbers:", evenNumbers) }

输出

Numbers: [2 4 1 3]

在这里,我们使用 append()oddNumbers 的元素添加到 evenNumbers 元素的列表中。


复制 Golang Slice

我们可以使用 copy() 函数将一个 slice 的元素复制到另一个 slice。例如,

// Program to copy one slice to another

package main
import "fmt"

func main() {

  // create two slices
  primeNumbers := []int{2, 3, 5, 7}
  numbers := []int{1, 2, 3}

// copy elements of primeNumbers to numbers copy(numbers, primeNumbers)
// print numbers fmt.Println("Numbers:", numbers) }

输出

Numbers: [2 3 5]

在上面的示例中,我们将 primeNumbers 的元素复制到 numbers

copy(numbers, primeNumbers)

在这里,只有 primeNumbers 的前 3 个元素被复制到 numbers。这是因为 numbers 的大小是 3,它只能容纳 3 个元素。

copy() 函数会用元素替换目标数组的所有元素。


查找 Slice 的长度

我们使用 len() 函数来查找 slice 中存在的元素数量。例如,

// Program to find the length of a slice

package main
import "fmt"

func main() {

  // create a slice of numbers
  numbers := []int{1, 5, 8, 0, 3}

// find the length of the slice length := len(numbers)
fmt.Println("Length:", numbers) }

输出

Length: 5

遍历 Go Slice

在 Go 中,我们可以使用 for 循环来遍历 slice。例如,

// Program that loops over a slice using for loop

package main
import "fmt"

func main() {
  numbers := []int{2, 4, 6, 8, 10}

// for loop that iterates through the slice for i := 0; i < len(numbers); i++ { fmt.Println(numbers[i]) }
}

输出

2
4
6
8
10

在这里,len() 函数返回 slice 的大小。slice numbers 的大小是 5,所以 for 循环会迭代 5 次。


常见问题

访问 Slice 的元素

在 Go 中,slice 中的每个元素都与一个数字相关联。这个数字称为 slice 索引。

我们可以使用索引号 (0, 1, 2 …) 来访问 slice 的元素。例如,

// Program to access the slice elements

package main
import "fmt"

func main() {

  languages := []string{"Go", "Java", "C++"}

  // access element at index 0
  fmt.Println(languages[0])

  // access element at index 2
  fmt.Println(languages[2])

  // access elements from index 0 to index 2
  fmt.Println(languages[0:3]) 

}

输出

Go
C++
[Go Java C++]

在上面的示例中,我们创建了一个名为 languages 的 slice。

Elements of slice with its respective index.
Slice 元素及其对应的索引。

在这里,我们可以看到每个 slice 元素都与索引号相关联。而且,我们使用了索引号来访问元素。

注意:slice 索引总是从 0 开始。因此,slice 的第一个元素位于索引 0,而不是 1

更改 Slice 的元素

我们可以使用相同的索引号来更改 slice 元素的值。例如,

package main
import "fmt"

func main() {
  weather := []string{"Rainy", "Sunny", "Cloudy"}

//change the element of index 2 weather[2] = "Stromy"
fmt.Println(weather) }

输出

[Rainy Sunny Stromy]

在这里,索引 2 的值从 "Cloudy" 更改为 "Stromy"

使用 make() 函数创建 Slice

在 Go 中,我们也可以使用 make() 函数来创建 slice。例如,

numbers := make([]int, 5, 7)

在这里,我们创建了一个整数类型的 slice。

  • 5 是 slice 的长度(slice 中元素的数量)
  • 7 是 slice 的容量(slice 可以扩展到的最大大小)

让我们看一个例子,

package main
import "fmt"

func main() {
    
// create a slice using make() numbers := make([]int, 5, 7)
// add elements to numbers numbers[0] = 13 numbers[1] = 23 numbers[2] = 33 fmt.Println("Numbers:", numbers) }

输出

Numbers: [13 23 33 0 0]

在这里,我们创建了长度为 5 的 slice。但是,我们只初始化了 3 个值到 slice。

在这种情况下,剩余的值被初始化为默认值 0

使用 for range 遍历 Slice

除了使用 for 循环,我们还可以使用 for range 来遍历 Golang 中的 slice。例如,

// Program that loops over a slice using for range loop

package main
import "fmt"

func main() {
  numbers := []int{2, 4, 6, 8, 10}

// for range loop that iterates through a slice for _, value := range numbers { fmt.Println(value) }
}

输出

2
4
6
8
10

在这里,for range 循环遍历 slice 的第一个元素 (2) 到最后一个元素 (10)。要了解 range,请访问 Go range

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战