码迷,mamicode.com
首页 > 编程语言 > 详细

Go语言 切片长度和容量

时间:2018-08-01 14:18:43      阅读:456      评论:0      收藏:0      [点我收藏+]

标签:Go语言   切片   slice   print   开头   nts   输出   fir   二次   

package main

import "fmt"

func main() {
	s := []int{2, 3, 5, 7, 11, 13}
	printSlice(s)

	// Slice the slice to give it zero length.
	s = s[:0]
	printSlice(s)

	// Extend its length.
	fmt.Println(s[:5])
	s = s[:4]
	printSlice(s)

	// Drop its first two values.
	s = s[2:]
	printSlice(s)
}

func printSlice(s []int) {
	fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

  

输出

len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
[2 3 5 7 11]
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]

  

第一次重新赋值s的指向底层数组的0   第二次s还是指向0  第三次指向了2 

一切都以开头的那个指向的index 开始切片的

cap就是当前切片的0指向的位置开始到end

  

如果不理解可以看下图

技术分享图片

 

Go语言 切片长度和容量

标签:Go语言   切片   slice   print   开头   nts   输出   fir   二次   

原文地址:https://www.cnblogs.com/shenwenlong/p/9400359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!