Skip to content

Instantly share code, notes, and snippets.

@5idu
Created April 15, 2019 14:41
Show Gist options
  • Save 5idu/5a8bb457a8338ec6aac4f17ebbb11ae1 to your computer and use it in GitHub Desktop.
Save 5idu/5a8bb457a8338ec6aac4f17ebbb11ae1 to your computer and use it in GitHub Desktop.
数组小知识点
### 数组
```go
slice := [...]int{1, 2, 3, 4, 5}
for _, v := range slice {
v = 0
fmt.Println(v)
// Output: 0
}
fmt.Println(slice)
// Output:
[1,2,3,4,5]
```
- for range循环中的值,只是原来数组中元素的拷贝,而不是元素的引用,所以对值的修改不能改变原来数组中的元素值
- 可以使用`slice[k] = x`去改变原始数组中元素的值
```go
slice := [...]int{1, 2, 3, 4, 5}
for i := 0; i < len(slice); i++ {
slice[i] = 0
}
fmt.Println(slice)
// Output:
[0,0,0,0,0]
```
- 可以在循环中改变数组中的值
```go
func main() {
array := [5]int{1: 2, 3:4}
modify(array)
fmt.Println(array)
}
func modify(a [5]int){
a[1] =3
fmt.Println(a)
}
// Output:
[0 3 0 4 0]
[0 2 0 4 0]
```
- 在函数间传递变量时,总是以值的方式,如果变量是个数组,那么就会整个复制,并传递给函数,如果数组非常大,比如长度100多万,那么这对内存是一个很大的开销
- 通过上面的例子,可以看到,数组是复制的,原来的数组没有修改
```go
func main() {
array := [5]int{1: 2, 3:4}
modify(&array)
fmt.Println(array)
}
func modify(a *[5]int){
a[1] =3
fmt.Println(*a)
}
// Output:
[0 3 0 4 0]
[0 3 0 4 0]
```
- 传递数组的指针,这样,复制的大小只是一个数组类型的指针大小
- 这是传递数组的指针的例子,会发现数组被修改了。所以这种情况虽然节省了复制的内存,但是要谨慎使用,因为一不小心,就会修改原数组,导致不必要的问题
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment