Go by Example 中文中推荐的一篇了解Slice的英文文章,看是不难看懂,但是看英文加整理真的好费劲,有这个时间看中文的估计已经看完了几倍的信息。下次还是不这样做了,太费时

目录

slice用途

Go中的Arrays

array的类型定义

go中数组变量和C语言中数组变量的不同

定义一个数组的两种方法

Slices

slice的数据类型

slice的一行语句创建方法

使用make()创建slice

Slice的内部实现(指向array的指针+length +capacity)

为Slice设计扩容和append方法

扩容方法的实现

append方法的实现(扩容之后再copy)

Slice内置的append方法

slice切片带来的内存浪费问题及其解决

造成内存浪费的代码

改进后的代码


slice用途

Go's slice type provides a convenient and efficient means of working with sequences of typed data.

Go中的Arrays

The slice type is an abstraction built on top of Go's array type, and so to understand slices we must first understand arrays.

array的类型定义

An array type definition specifies a length and an element type

For example, the type [4]int represents an array of four integers. An array's size is fixed; its length is part of its type ([4]int and [5]int are distinct, incompatible types).

go中数组变量和C语言中数组变量的不同

go中数组变量代表的是整个数组,而C中代表指向数组的指针

Go's arrays are values. An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C). This means that when you assign or pass around an array value you will make a copy of its contents. (To avoid the copy you could pass a pointer to the array, but then that's a pointer to an array, not an array.) One way to think about arrays is as a sort of struct but with indexed rather than named fields: a fixed-size composite value.

定义一个数组的两种方法

An array literal can be specified like so:

b := [2]string{"Penn", "Teller"}

Or, you can have the compiler count the array elements for you:

b := [...]string{"Penn", "Teller"}

In both cases, the type of b is [2]string.

Slices

slice的数据类型

The type specification for a slice is []T, where T is the type of the elements of the slice. Unlike an array type, a slice type has no specified length.

slice的一行语句创建方法

A slice literal is declared just like an array literal, except you leave out the element count:

letters := []string{"a", "b", "c", "d"}

使用make()创建slice

其中参数len、cap作用的进一步说明见 Golang make多种使用方法详解_阿俊的博客-CSDN博客_golang make

A slice can be created with the built-in function called make, which has the signature,

func make([]T, len, cap) []T

where T stands for the element type of the slice to be created. The make function takes a type, a length, and an optional capacity. When called, make allocates an array and returns a slice that refers to that array.

var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}

When the capacity argument is omitted, it defaults to the specified length. Here's a more succinct version of the same code:

s := make([]byte, 5)

The length and capacity of a slice can be inspected using the built-in len and cap functions.

len(s) == 5
cap(s) == 5

Slice的内部实现(指向array的指针+length +capacity)

A slice is a descriptor of an array segment. It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).

Our variable s, created earlier by make([]byte, 5), is structured like this:

The length is the number of elements referred to by the slice. The capacity is the number of elements in the underlying array (beginning at the element referred to by the slice pointer). The distinction between length and capacity will be made clear as we walk through the next few examples.

As we slice s, observe the changes in the slice data structure and their relation to the underlying array:

s = s[2:4]

Slicing does not copy the slice's data. It creates a new slice value that points to the original array. This makes slice operations as efficient as manipulating array indices. Therefore, modifying the elements (not the slice itself) of a re-slice modifies the elements of the original slice:

d := []byte{'r', 'o', 'a', 'd'}
e := d[2:]
// e == []byte{'a', 'd'}
e[1] = 'm'
// e == []byte{'a', 'm'}
// d == []byte{'r', 'o', 'a', 'm'}

Earlier we sliced s to a length shorter than its capacity. We can grow s to its capacity by slicing it again:

s = s[:cap(s)]

A slice cannot be grown beyond its capacity. Attempting to do so will cause a runtime panic, just as when indexing outside the bounds of a slice or array. Similarly, slices cannot be re-sliced below zero to access earlier elements in the array.

为Slice设计扩容和append方法

扩容方法的实现

To increase the capacity of a slice one must create a new, larger slice and copy the contents of the original slice into it. This technique is how dynamic array implementations from other languages work behind the scenes. The next example doubles the capacity of s by making a new slice, t, copying the contents of s into t, and then assigning the slice value t to s:

t := make([]byte, len(s), (cap(s)+1)*2) // +1 in case cap(s) == 0
for i := range s {t[i] = s[i]
}
s = t

The looping piece of this common operation is made easier by the built-in copy function. As the name suggests, copy copies data from a source slice to a destination slice. It returns the number of elements copied.

func copy(dst, src []T) int

The copy function supports copying between slices of different lengths (it will copy only up to the smaller number of elements). In addition, copy can handle source and destination slices that share the same underlying array, handling overlapping slices correctly.

Using copy, we can simplify the code snippet above:

t := make([]byte, len(s), (cap(s)+1)*2)
copy(t, s)
s = t

append方法的实现(扩容之后再copy)

A common operation is to append data to the end of a slice. This function appends byte elements to a slice of bytes, growing the slice if necessary, and returns the updated slice value:

func AppendByte(slice []byte, data ...byte) []byte {m := len(slice)n := m + len(data)if n > cap(slice) { // if necessary, reallocate// allocate double what's needed, for future growth.newSlice := make([]byte, (n+1)*2)copy(newSlice, slice)slice = newSlice}slice = slice[0:n]copy(slice[m:n], data)return slice
}

One could use AppendByte like this:

p := []byte{2, 3, 5}
p = AppendByte(p, 7, 11, 13)
// p == []byte{2, 3, 5, 7, 11, 13}

Slice内置的append方法

But most programs don't need complete control, so Go provides a built-in append function that's good for most purposes; it has the signature

func append(s []T, x ...T) []T

The append function appends the elements x to the end of the slice s, and grows the slice if a greater capacity is needed.

a := make([]int, 1)
// a == []int{0}
a = append(a, 1, 2, 3)
// a == []int{0, 1, 2, 3}

To append one slice to another, use ... to expand the second argument to a list of arguments.

a := []string{"John", "Paul"}
b := []string{"George", "Ringo", "Pete"}
a = append(a, b...) // equivalent to "append(a, b[0], b[1], b[2])"
// a == []string{"John", "Paul", "George", "Ringo", "Pete"}

slice切片带来的内存浪费问题及其解决

根据前面说的对slice内部实现,对slice重新切片并不会产生一个新的数组,只是产生了一个新的指针指向。有时我们只是从数组中切片截取出一小部分对我们有用的信息,之后整个数组就不需要继续保持在内存当中了,但是,只要还存在对该数组的引用整个数组都会一直被保存在内存中而不会被垃圾回收器释放。

造成内存浪费的代码

For example, this FindDigits function loads a file into memory and searches it for the first group of consecutive numeric digits, returning them as a new slice.

var digitRegexp = regexp.MustCompile("[0-9]+")func FindDigits(filename string) []byte {b, _ := ioutil.ReadFile(filename)return digitRegexp.Find(b)
}

This code behaves as advertised, but the returned []byte points into an array containing the entire file. Since the slice references the original array, as long as the slice is kept around the garbage collector can't release the array; the few useful bytes of the file keep the entire contents in memory.

改进后的代码

To fix this problem one can copy the interesting data to a new slice before returning it:

func CopyDigits(filename string) []byte {b, _ := ioutil.ReadFile(filename)b = digitRegexp.Find(b)c := make([]byte, len(b))copy(c, b)return c
}

A more concise version of this function could be constructed by using append. This is left as an exercise for the reader.

Go 中 slice 的设计和实现细节(Go 团队撰写的一篇很棒的博文)相关推荐

  1. java 内存同步_Java中的硬件事务性内存,或者为什么同步将再次变得很棒

    java 内存同步 总览 硬件事务内存有可能允许多个线程同时以推测方式访问相同的数据结构,并使缓存一致性协议确定是否发生冲突. HTM旨在为您提供细粒度锁定的可伸缩性,粗粒度锁定的简单性以及几乎没有锁 ...

  2. Java中的硬件事务性内存,或者为什么同步将再次变得很棒

    总览 硬件事务内存有潜力允许多个线程同时以推测方式访问相同的数据结构,并使缓存一致性协议确定是否发生冲突. HTM旨在为您提供细粒度锁定的可伸缩性,粗粒度锁定的简单性以及几乎没有锁定的性能. 如果JV ...

  3. 分享25个很棒的网页设计教程和资源网站

    如果你是一个初学者,你想找高质量的设计资源和高品质的网页设计教程,可以看看本文列出的25个很棒的网页设计教程和资源网站,如果你是高手,也可以把自己制作的设计教程发布到这些网站上,这样更多人能够从你的教 ...

  4. mysql网页设计资源_分享25个很棒的网页设计教程和资源网站

    如果你是一个初学者,你想找高质量的设计资源和高品质的网页设计教程,可以看看本文列出的25个很棒的网页设计教程和资源网站,如果你是高手,也可以把自己制作的设计教程发布到这些网站上,这样更多人能够从你的教 ...

  5. AI中pass架构设计优化

    AI中pass架构设计优化 Relay 和 TVM IR,包含一系列优化passes,可提高模型的性能指标,例如平均推理,内存占用,或特定设备的功耗.有一套标准优化,及特定机器学习的优化,包括常量折叠 ...

  6. 面试官系统精讲Java源码及大厂真题 - 36 从容不迫:重写锁的设计结构和细节

    36 从容不迫:重写锁的设计结构和细节 受苦的人,没有悲观的权利. --尼采 引导语 有的面试官喜欢让同学在说完锁的原理之后,让你重写一个新的锁,要求现场在白板上写出大概的思路和代码逻辑,这种面试题目 ...

  7. directui 3d界面引擎_美术设计师浅谈AR/VR中3D建模设计的工具、挑战与区别

    (映维网 2019年04月20日)3D越来越受欢迎,并对每个人的生活都产生了影响.从建筑到娱乐,许多不同的领域都有利用3D技术.例如詹姆斯·卡梅隆的<阿凡达>,这部电影给我们带来了前所未有 ...

  8. 架构的坑系列:重构过程中的过度设计

    架构的坑系列:重构过程中的过度设计 软件架构   2016-06-03 08:47:02 发布 您的评价:       5.0   收藏     2收藏 这个系列是 坑 系列,会说一些在系统设计,系统 ...

  9. UI设计中搜索页设计指南

    在开始之前,我们先来想一个问题,用户为什么要使用搜索功能呢? 今天我带大家一起来探讨一下UI搜索页面的一些设计方法. 用户搜索的目的是为了快速找到自己想要的结果!搜索页是用户进行搜索的第一站,最理想的 ...

最新文章

  1. WebAPI接口安全校验
  2. Mac及Xcode常用快捷键
  3. 威海二职工业机器人专业_工业机器人专业就业前景-山东省好的中专学校
  4. Qt工作笔记-undefined reference to `vtable for MyObject'及对moc文件的进一步理解
  5. jQuery+css3实现新年贺卡
  6. plSql安装以及连接远程oracle相关配置
  7. linux chmod修改权限失败,Linux chmod修改文件夹权限
  8. SSAS的MDX的基础函数(三),及聚合函数
  9. 国产杀毒软件连续因“作弊”遭全球权威评测机构指责
  10. 对网易云音乐软件的看法
  11. 完全免费的在线遥感影像下载器-转载
  12. 【bzoj2959】长跑【LCT+并查集】
  13. 英语四六级考试技巧/英语四六级真题
  14. html文件关联异常怎么修复,在Win7系统中,如何修复exe文件关联错误?
  15. MPB:中科院植物所杨文强组-​莱茵衣藻遗传连锁分析方法
  16. POI 2011 切题记
  17. 计算机打字教程ppt,计算机打字基础教学.ppt
  18. deepin终端编译c程序_Deepin系统安装软件总结:通过商店、二进制包、deb包、终端命令安装...
  19. JavaScript中如何用函数求任意两数之和?
  20. 目前用于微型计算机系统的光盘有哪些,目前用于计算机系统的光盘,分为这三类...

热门文章

  1. maskrcnn_benchmark 代码详解之 boxlist_ops.py
  2. 1660s功耗多少w_gtx660满载功耗是多少
  3. B2B2C网上商城开发指南——基于SaaS和淘宝API开放平台
  4. tcp/ip通讯 linux xpe,XPE最基本组件 分享
  5. 【leetcode】脑子打结的题
  6. Excel中批量快速删除空行
  7. 华为路由器修改telnet,ssh密码
  8. 长为一名JAVA架构师2017-10-16 2
  9. 十三位时间戳转换工具_展览 | “无缘无故—十三位当代女性艺术家邀请展”亮相朗空美术馆...
  10. 基于阿里云的基础架构设施保障(二)IAAS云存储