Golang 初始化切片
在本文中,我们将学习如何使用各种方法初始化切片的示例。切片是一系列元素,就像数组一样。数组是一个固定的元素序列,而切片是一个动态数组,这意味着它的值不固定,可以更改。切片比数组更高效和更快,而且它们是按引用传递而不是按值传递。让我们通过示例来学习如何执行它。
步骤
- 第1步 - 创建一个名为main的包,并在程序中声明fmt(format包)包,其中main生成可执行代码,fmt用于格式化输入和输出。
-
第2步 - 创建一个名为main的函数,并在该函数中使用make函数初始化一个切片,该函数有两个参数:长度和容量。
-
第3步 - 在控制台上打印使用make函数初始化的切片。
-
第4步 - 使用fmt.Println()函数执行打印语句,其中ln表示换行。
语法
func make ([] type, size, capacity)
make函数用于在go语言中创建数组/映射,它接受要创建的变量类型、大小和容量作为参数
func append(slice, element_1, element_2…, element_N) []T
append函数用于将值添加到数组切片。它接受多个参数。第一个参数是我们希望将值添加到的数组,其后是要添加的值。函数然后返回包含所有值的最终数组切片。
使用Make函数
在这个示例中,我们将学习如何使用make函数初始化一个切片。它是一种内置函数,其工作原理如下所述。让我们通过算法和代码来理解它是如何解决这个问题的。
示例
package main
import "fmt"
func main() {
slice := make([]int, 2, 4) // create slice using make function
fmt.Println("The slice created here has a length of:", slice) //print slice
}
输出
The slice created here has a length of: [0 0]
使用速记声明
在此示例中,我们将学习如何使用速记声明初始化一个切片。使用Golang中的打印语句将创建的切片打印到控制台上。让我们通过算法和代码来理解这个概念。
示例
package main
import "fmt"
func main() {
// creates a slice with elements
slice := []int{1, 2, 3}
fmt.Println("The slice created here is:")
fmt.Println(slice) // print the slice
}
输出
The slice created here is:
[1 2 3]
使用append语句
在这个示例中,我们将使用append函数初始化一个切片,其功能如下所述。在这里,我们将通过算法和代码来理解这个概念。
示例
package main
import "fmt"
func main() {
var slice []int
slice = append(slice, 1) //fill the elements in slice using append function
slice = append(slice, 2)
slice = append(slice, 3)
fmt.Println("The slice created is:")
fmt.Println(slice) // print the slice
}
输出
The slice created is:
[1 2 3]
使用for循环在append函数中
在这个示例中,我们将使用一个for循环在append函数中初始化一个切片。使用循环帮助我们为切片分配元素。让我们通过算法和代码来理解它。
示例
package main
import "fmt"
func main() {
// create an empty slice
slice := []int{}
for i := 0; i < 4; i++ {
slice = append(slice, i) // append the elements in slice using append function
}
fmt.Println("The slice created here is:")
fmt.Println(slice) // print the slice
}
输出
The slice created here is:
[0 1 2 3]
结论
在上述的程序中,我们使用了四个示例来初始化一个切片。在第一个示例中,我们使用了make函数来创建一个切片。在第二个示例中,我们使用了简写声明。在第三个示例中,我们使用了append函数来创建一个切片。在第四个示例中,我们使用了for循环来在屏幕上打印切片。因此,程序成功地执行了。
极客笔记