golang 基础语法需要注意的

时间:2023-02-23 08:59:20


1. for range遍历切片, map

package main
import (
"fmt"
)
func Sum(set []int) int {
var result int
//for num := range set { //这个的num是索引,正确的写法是 for _, value := range set{
for _, num := range set{ // range很奇怪,又能返回一个值,又能返回2个值
result += num
}
return result
}
func main() {
set := []int{17, 23, 100, 76, 55}
sum := Sum(set)
fmt.Printf("sum is : %d", sum)
}