网站首页 > 文章中心 > 其它

go语言slice用法_go语言中make的用法

作者:小编 更新时间:2023-09-04 11:13:05 浏览量:223人看过

go语言中数组使用的注意事项和细节

①.、数组是多个 相同类型 的数据的组合,一个数组一旦声明/定义了,其 长度是固定的,不能动态变化 .

go语言slice用法_go语言中make的用法-图1

? ? ? 数值类型数组:?默认值为 0

? ? ? 字符串数组:? ? ? ?默认值为 ""

? ? ? bool数组:? ? ? ? ? ?默认值为 false

? ? ? (1)声明数组并开辟空间

①.0、长度是数组类型的一部分,在传递函数参数时,需要考虑数组的长度,看以下案例:

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:

go语言slice用法_go语言中make的用法-图2

运行结果如下

由此可见,执行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语言"奇怪用法"有哪些

①.,go的变量声明顺序是:"先写变量名,再写类型名",此与C/C++的语法孰优孰劣,可见下文解释:

①.0,go语言只有一个循环结构——for循环.

①.1,go里的自增运算符只有——"后++"

以上就是土嘎嘎小编为大家整理的go语言slice用法相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!

版权声明:倡导尊重与保护知识产权。未经许可,任何人不得复制、转载、或以其他方式使用本站《原创》内容,违者将追究其法律责任。本站文章内容,部分图片来源于网络,如有侵权,请联系我们修改或者删除处理。

编辑推荐

热门文章