首页 > 后端开发 > Golang > 正文

Append() 如何影响 Go 中的切片?

Mary-Kate Olsen
发布: 2024-11-15 13:54:02
原创
619 人浏览过

How Does append() Affect Slices in Go?

Understanding the Behavior of append() on Slices

Despite the initial assumptions of slice as a pointer, the provided code demonstrates that the append() operation does not directly affect the original slice. This is because, in Go, everything is passed by value, including slices. So when you pass a slice to a function or assign it to a new variable, you are only passing a copy of the slice header.

The slice header contains information such as the length of the slice, its capacity, and a pointer to the underlying array. When the append() operation is performed on a slice, a new array is allocated if necessary to accommodate the new elements. The slice header is then updated to point to the new array, and the new elements are copied over. This new slice header is returned as the result of the append() call.

In the example code, you assign the return value of the append() operation to the slice1 variable. This means that slice1 now points to a different array than slice. Any changes made to the elements of slice1 will not be reflected in slice, and vice versa.

To achieve the behavior where both slice and slice1 refer to the same array, you would need to use a pointer to a slice instead of a slice itself. For example:

func main() {
    slice := make([]int, 10, 10)
    slice[0] = 0
    slice[1] = 1

    slicePtr := &slice
    slice1 := *slicePtr
    slice1[0] = 10000
    fmt.Println(slice)

    *slicePtr = append(*slicePtr, 100)
    (*slicePtr)[0] = 20000

    fmt.Println(slice)
}
登录后复制

In this example, both slice and slice1 point to the same underlying array, so any changes made to one will be visible in the other.

以上是Append() 如何影响 Go 中的切片?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板