当前位置:网站首页>Slice切片
Slice切片
2022-07-28 04:05:00 【紫罗兰与海棠】
一、定义切片
声明一个未指定大小的数组来定义切片,切片不需要说明长度
var identifier []type
使用make()函数创建切片
var slice1 []type = make([]type, len)
//简写
slice1 := make([]type, len)
//指定容量,其中 capacity 为可选参数
//len 是数组的长度并且也是切片的初始长度
make([]T, length, capacity)
二、初始化
直接初始化切片
s := []int{
1, 2, 3}
初始化切片 s,是数组 arr 的引用
s := arr[:]
将 arr 中从下标 startIndex 到 endIndex-1 下的元素创建为一个新的切片
s := arr[startIndex:endIndex]
默认 endIndex 时将表示一直到arr的最后一个元素
s := arr[startIndex:]
默认 startIndex 时将表示从 arr 的第一个元素开始
s := arr[:endIndex]
通过切片 s 初始化切片 s1
s1 := s[startIndex:endIndex]
通过内置函数 make() 初始化切片s,[]int 标识为其元素类型为 int 的切片
s := make([]int,len,cap)
三、len()和cap()函数
- len():获取长度
- cap():计算容量
- 一个切片在未初始化之前默认为 nil,长度为 0
四、截取
通过设置下限及上限来设置截取切片 [lower-bound:upper-bound]
number1 := numbers[:2]
五、添加元素 append()
向切片追加新元素
/* 向切片添加一个元素 */
numbers = append(numbers, 1)
printSlice(numbers)
/* 同时添加多个元素 */
numbers = append(numbers, 2,3,4)
printSlice(numbers)
六、复制切片元素到另一个切片 copy()
拷贝切片
/* 拷贝 numbers 的内容到 numbers1 */
copy(numbers1,numbers)
七、删除元素
seq := []string{
"a", "b", "c", "d", "e"}
index := 2
//...表示将seq[index+1:]整个添加到seq[:index]后面
seq = append(seq[:index], seq[index+1:]...)
边栏推荐
- WordPress simple mkblog blog theme template v2.1
- Data mining-02
- Lightpicture - exquisite drawing bed system
- Advanced Mathematics (Seventh Edition) Tongji University exercises 3-4 personal solutions (first 8 questions)
- Experience sharing of automatic test for students with monthly salary of 28K
- Appnium--APP自动化测试工具
- servlet使用
- Protocols in swift
- C语言力扣第45题之跳跃游戏 II。遍历跳跃
- Is there a bonus period for robot engineering
猜你喜欢

Un7.27: how to successfully build a ruoyi framework project in idea?

Monotonic stack - 739. Daily temperature

H265/HEVC名词解释-- CTU,CTB,CU,CB,TU,PU,TB,PB,LCU,Slice,Tile,Chroma,Luma,I帧,B帧,P帧

Common interface testing tools

LeetCode 0141. 环形链表 - 三种方法解决

Filters, interceptors, listeners
![[untitled]](/img/6c/df2ebb3e39d1e47b8dd74cfdddbb06.gif)
[untitled]

Basic knowledge of day08 redis
![Error no matching function for call to 'std:: exception:: exception (const char [15])' problem solving](/img/d1/2fbdf42cf60b5382b5a35c64b172b9.png)
Error no matching function for call to 'std:: exception:: exception (const char [15])' problem solving

【无标题】
随机推荐
Data rich Computing: m.2 meets AI at the edge
CV2. Threshold(), CV2. Findcontours(), CV2. Findcontours image contour processing
Skillfully use stack backtracking to help you quickly locate problems
常用的接口测试工具
Linux - MySQL advanced (day19)
[MySQL database] index and transaction (often used in interview)
Fourier series
MySQL是怎么保证高可用的
Shell rental reptile
[day03] process control statement
pl/sql之各参数详解(“箱子模型“)
Classification cluster analysis
Detailed explanation of pointer written test questions (C language)
离职前一定要做好这7件事情,少一件都很麻烦。
《剑指offer》| 刷题小记
un7.27:如何在idea中成功搭建若依框架项目?
Machine learning 06: Decision Tree Learning
金仓数据库KingbaseES安全指南--5.1. 数据库的传输安全
Dynamic planning - 62. Different paths
Leetcode58. 最后一个单词的长度