golang小记

切片与数据

学golang时,书上提过从数组生成切片时,切片实际上是有一个指针指向那个数组,所以对切片和数组的操作会相互影响。

好奇的是切片是变长的,当切片超过原生数组长度后,还会保持那个指针么,或者有更高级的方式,今天试了一下,比较失望的是,对切片执行append操作,当超过该切片的capacity时,go会分配一个新的数组给切片,两者从此分道扬镳。

append操作会在切片底层数组不够时分配新数组,所以使用切片的话,最好还是得计算要用的空间大小。

可能是最近受函数式编程的immutable variable影响,总觉得切片跟数组共享同一片内存会有点危险。

函数式语言中有大量的复制操作,处于性能及内存考虑,他们的集合实现应该跟普通的集合不一样,有空去看看它们的实现。

New and Make

Go has two data structure creation functions: new and make. The distinction is a common early point of confusion but seems to quickly become natural. The basic distinction is that new(T) returns a *T, a pointer that Go programs can dereference implicitly (the black pointers in the diagrams), while make(T, args) returns an ordinary T, not a pointer. Often that T has inside it some implicit pointers (the gray pointers in the diagrams). New returns a pointer to zeroed memory, while make returns a complex structure.

简单的说,new返回指针,make返回值,但这个值底层通常含有指针。

以上英语部分转自http://research.swtch.com/godata

本文来自:开源中国博客

感谢作者:Bluven

查看原文:golang小记

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。