go的切片下标取值

版权声明:微信公众号 java架构狮 欢迎转载 请注明出处 https://blog.csdn.net/AlbertFly/article/details/89081725
s := arr[startIndex:endIndex] 

将arr中从下标startIndex到endIndex-1 下的元素创建为一个新的切片

package main

import "fmt"

func sum(s []int, c chan int) {
	sum := 0
	for _, v := range s {
		sum += v
	}
	c <- sum // 把 sum 发送到通道 c
}

func main() {
	s := []int{7, 2, 8, -9, 4, 0}

	c := make(chan int)
	fmt.Println(s[5])
	fmt.Println(s[:len(s)/2])
	go sum(s[:len(s)/2], c)
	go sum(s[len(s)/2:], c)
	x, y := <-c, <-c // 从通道 c 中接收
	fmt.Println(x, y, x+y)
	// sun1 : 8, 4, 12
}

输出:

0
[7 2 8]
-5 17 12

猜你喜欢

转载自blog.csdn.net/AlbertFly/article/details/89081725