GO语言学习——切片二
2022-04-29 00:09
1676 查看
使用make()函数构造切片
格式:
make([]T, size, cap)
其中:
- T:切片的元素类型
- size:切片中元素的数量
- cap:切片的容量
切片的本质
切片的本质就是对底层数组的封装,它包含了三个信息:
- 底层数组的指针
- 切片的长度(len)
- 切片的容量(cap)
切片的本质
切片就是一个框,框住了一块连续的内存。
切片属于引用类型,真正的数据都是保存在底层数组里的。
判断切片是否为空
使用len(s) == 0来判断
切片不能直接比较
一个nil值的切片没有底层数组
一个nil值的切片的长度和容量都是0
一个长度和容量都是0的切片不一定是nil
切片的赋值拷贝
切片遍历
索引遍历和
for range遍历
package main import "fmt" // make()函数创造切片 func main(){ s1 := make([]int,5,10) fmt.Printf("s1=%v len(s1)=%d cap(s1)=%d\n", s1, len(s1), cap(s1)) // s1=[0 0 0 0 0] len(s1)=5 cap(s1)=10 s2 := make([]int,0,10) fmt.Printf("s2=%v len(s2)=%d cap(s2)=%d\n", s2, len(s2), cap(s2)) // s2=[] len(s2)=0 cap(s2)=10 // 切片的赋值 s3 := []int{1,3,5} s4 := s3 // s3和s4都指向了同一个底层数组 fmt.Println(s3, s4) s3[0] = 1000 fmt.Println(s3, s4) // 切片的遍历 // 1. 索引遍历 for i:=0;i<len(s3);i++ { fmt.Println(s3[i]) } // 2. for range循环 for i,v := range s3 { fmt.Println(i, v) } }
vscode 配置代码片段
Ctrl + Shift + P snippets go(go.json)
{ // Place your snippets for go here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are: // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the // same ids are connected. // Example: // "Print to console": { // "prefix": "log", // "body": [ // "console.log('$1');", // "$2" // ], // "description": "Log output to console" // } "println":{ "prefix": "pln", "body":"fmt.Println($0)", "description": "println" }, "printf":{ "prefix": "plf", "body": "fmt.Printf(\"$0\")", "description": "printf" } }
相关文章推荐
- Go语言学习笔记四--数组与切片
- GO语言学习——切片三 append()方法为切片添加元素、切片的扩容策略、使用copy()函数复制切片、从切片中删除元素
- go语言学习——变量、常量、循环、条件、switch、数组和切片
- Go语言学习八:切片(slice)和范围(range)
- Go学习 数组和切片
- ps 切片学习记录
- cocos2d-x学习笔记20:切片动画库编写要点
- Go语言学习笔记 —— break控制语句
- python学习笔记之切片(slice)、列表生成式
- cocos2d学习记录(六)-切片动画
- python2.7学习笔记(6) ——高级特性:切片、迭代、列表生成式、生成器
- 学习笔记(02):零基础搞定Python数据分析与挖掘-字符串构造与索引、切片的使用(二)...
- Go语言学习之数据类型以及类型转换(The way to go)
- 【worldwind学习】worldwind android版添加天地图切片图层
- Go语言并发与并行学习笔记(一)
- go语言log包的学习(log,Logger)
- Go语言学习9-结构体类型
- Go语言核心36讲(Go语言进阶技术十四)--学习笔记
- Go语言学习笔记十一: 切片(slice)
- 零基础学习Go语言