go语言基础之切片和底层数组关系

1、切片和底层数组关系

示例:

package main //必须有个main包

import "fmt"

func main() {
	a := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

	//新切片
	s1 := a[2:5] //从a[2]开始,取3个元素
	s1[1] = 666
	fmt.Println("s1 = ", s1) //[2 3 4]
	fmt.Println("a = ", a)   //[2 666 4]

	//另外新切片
	s2 := s1[2:7]
	s2[2] = 777
	fmt.Println("s2 = ", s2) //[4 5 777 7 8]
	fmt.Println("a = ", a)   //[0 1 2 666 4 5 777 7 8 9]
}

执行结果:

s1 =  [2 666 4]
a =  [0 1 2 666 4 5 6 7 8 9]
s2 =  [4 5 777 7 8]
a =  [0 1 2 666 4 5 777 7 8 9]

  

 

posted @ 2019-01-09 14:23  努力哥  阅读(861)  评论(0编辑  收藏  举报