go语言slice使用 go语言strconv

golang变量(二)——map和slice详解衍生类型,interface{} , map, []  , struct等
map类似于java的hashmap , python的dict,php的hash array 。
常规的for循环,可以用for k,v :=range m {}. 但在下面清空有一个坑注意:
著名的map[string]*struct 副本问题
结果:
Go 中不存在引用传递,所有的参数传递都是值传递,而map是等同于指针类型的,所以在把map变量传递给函数时,函数对map的修改,也会实质改变map的值 。
slice类似于其他语言的数组(list,array),slice初始化和map一样,这里不在重复
除了Pointer数组外,len表示使用长度,cap是总容量,make([]int, len, cap)可以预申请 比较大的容量,这样可以减少容量拓展的消耗 , 前提是要用到 。
cap是计算切片容量 , len是计算变量长度的,两者不一样 。具体例子如下:
结果:
分析:cap是计算当前slice已分配的容量大小,采用的是预分配的伙伴算法(当容量满时,拓展分配一倍的容量) 。
append是slice非常常用的函数,用于添加数据到slice中,但如果使用不好,会有下面的问题:
预期是[1 2 3 4 5 6 7 8 9 10],[1 2 3 4 5 6 7 8 9 10 11 12],但实际结果是:
【go语言slice使用 go语言strconv】 注意slice是值传递,修改一下:
输出如下:
== 只能用于判断常规数据类型,无法使用用于slice和map判断,用于判断map和slice可以使用reflect.DeepEqual,这个函数用了递归来判断每层的k,v是否一致 。
当然还有其他方式,比如转换成json,但小心有一些异常的bug,比如html编码,具体这个json问题,待后面在分析 。
golang-101-hacks(12)——切片作为函数参数传递注:本文是对 golang-101-hacks 中文翻译 。
在Go语言中,函数参数是值传递 。使用slice作为函数参数时,函数获取到的是slice的副本:一个指针 , 指向底层数组的起始地址,同时带有slice的长度和容量 。既然各位熟知数据存储的内存的地址,现在可以对切片数据进行修改 。让我们看看下面的例子:
In Go, the function parameters are passed by value. With respect to use slice as a function argument, that means the function will get the copies of the slice: a pointer which points to the starting address of the underlying array, accompanied by the length and capacity of the slice. Oh boy! Since you know the address of the memory which is used to store the data, you can tweak the slice now. Let's see the following example:
运行结果如下
由此可见,执行modifyValue函数,切片s的元素发生了变化 。尽管modifyValue函数只是操作slice的副本,但是任然改变了切片的数据元素,看另一个例子:
You can see, after running modifyValue function, the content of slice s is changed. Although the modifyValue function just gets a copy of the memory address of slice's underlying array, it is enough!
See another example:
The result is like this:
而这一次,addValue函数并没有修改main函数中的切片s的元素 。这是因为它只是操作切片s的副本 , 而不是切片s本身 。所以如果真的想让函数改变切片的内容 , 可以传递切片的地址:
This time, the addValue function doesn't take effect on the s slice in main function. That's because it just manipulate the copy of the s, not the "real" s.
So if you really want the function to change the content of a slice, you can pass the address of the slice:
运行结果如下
go语言中实现切片(slice)的三种方式定义一个切片,然后让切片去引用一个已经创建好的数组 。基本语法如下:
索引1:切片引用的起始元素位
索引2:切片只引用该元素位之前的元素

推荐阅读