Golang程序 计算分片元素
在这篇文章中,我们将通过一组不同的例子来学习如何计算一个片断的元素。分片是一个元素序列,就像一个数组。数组是一个固定的元素序列,而片断是一个动态数组,意味着它的值不是固定的,可以改变。此外,切片比数组更有效、更快速;它们是通过引用而不是通过值传递。让我们通过例子来学习如何执行它。
语法
func append(slice, element_1, element_2…, element_N) []T
append函数用于向一个数组片断添加值。它需要一些参数。第一个参数是我们希望添加的数组,后面是要添加的值。然后,该函数返回包含所有值的数组的最终片断。
算法
- 第1步 – 创建一个包main,并在程序中声明fmt(format package)包,main产生可执行代码,fmt帮助格式化输入和输出。
-
第2步 – 初始化一个片断,并在其中填入一些数值,这些数值将通过append函数来计算。
-
第3步 – 使用print语句在控制台打印所创建的片断。
-
第4步– 使用长度函数计算分片中的元素,用len表示。
-
第5步 – 这里在for循环中使用了范围,而不是空白空间,以包括切片中的索引。
-
第6步 – 使用print语句在控制台打印所创建的片断的长度。
-
第7步 – 使用fmt.Println()函数执行打印语句,ln表示新行。
使用Len方法
在这个例子中,我们将看到如何使用len方法来计算片断的元素。len用于计算片断的长度。让我们通过算法和代码看看它是如何完成的。
例子
package main
import "fmt"
func main() {
var slice []int // create a slice
slice = append(slice, 10) //fill the elements in slice using append function
slice = append(slice, 20)
slice = append(slice, 30)
length_slice := len(slice) //calculate length of slice using len method
fmt.Println("The elements of slice are:", slice) //print slice elements
fmt.Println("The slice has", length_slice, "elements.") //print length of slice
}
输出
The elements of slice are: [10 20 30]
The slice has 3 elements.
使用For循环和计数变量
在这个例子中,我们将看到如何使用for循环来计算一个片断的元素。For循环将被用来通过在每次迭代中增加元素来计算片断的长度。让我们通过算法和代码看看它是如何完成的。
例子
package main
import "fmt"
func main() {
var slice []int
slice = append(slice, 10) //fill the elements in slice using append function
slice = append(slice, 20)
slice = append(slice, 30)
fmt.Println("The elements in slice are:", slice) //print slice elements
count := 0 //count to store number of elements in slice
for range slice { //for loop runs till length of slice
count++
}
fmt.Println("The slice has", count, "elements.") //print the length of slice
}
输出
The elements in slice are: [10 20 30]
The slice has 3 elements.
结论
我们在上面的两个例子中执行了计算分片元素的程序。在第一个例子中,我们使用len方法来计算切片中的元素,在第二个例子中,我们使用for循环来计算每个迭代中的切片元素。在这两个例子中,我们都使用了append函数将元素添加到片断中,从而缩短了代码。