简体   繁体   English

Golang 指向切片的指针

[英]Golang pointer to a slice

I was recently doing a backtracking question and came across this weird scenario which I am not able to understand.我最近在做一个回溯问题,遇到了这个我无法理解的奇怪场景。 This question is related to listing out all the possible subsets possible from the given array.这个问题与列出给定数组中所有可能的子集有关。 Here is the code snippet:这是代码片段:

func subsets(A []int) [][]int {
    sort.Ints(A)
    res, cur := [][]int{}, []int{}
    if len(A) == 0 {
        return append(res, cur)
    }
    subsetsUtil(A, 0, &res, cur)
    return res
}

func subsetsUtil(A []int, n int, res *[][]int, cur []int) {
    *res = append(*res, append([]int{}, cur...))
    for i := n; i < len(A); i++ {
        cur = append(cur, A[i])
        subsetsUtil(A, i+1, res, cur)
        cur = cur[:len(cur)-1]
    }
}

This code snippet gives me the correct answer but if I remove the pointer to the result slice, ie此代码片段给了我正确的答案,但如果我删除指向结果切片的指针,即

func subsets(A []int) [][]int {
    sort.Ints(A)
    res, cur := [][]int{}, []int{}
    if len(A) == 0 {
        return append(res, cur)
    }
    subsetsUtil(A, 0, res, cur)
    return res
}

func subsetsUtil(A []int, n int, res [][]int, cur []int) {
    res = append(res, append([]int{}, cur...))
    for i := n; i < len(A); i++ {
        cur = append(cur, A[i])
        subsetsUtil(A, i+1, res, cur)
        cur = cur[:len(cur)-1]
    }
}

Code doesn't work and returns me an empty slice.代码不起作用并返回一个空切片。 As far as I understand, slices are passed by reference and not by value, then how is it when I pass the pointer to the result slice, code works and gives me the correct result but for the other case, it is returning me an empty slice?据我了解,切片是通过引用而不是值传递的,那么当我将指针传递给结果切片时,代码如何工作并给我正确的结果,但对于另一种情况,它返回给我一个空片? What am I missing?我错过了什么?

This statement: "As far as I understand, slices are passed by reference and not by value" is not entirely true.这种说法:“据我所知,切片是通过引用而不是通过值传递的”并不完全正确。 Slices are not pure reference types but an aggregate type such as this struct:切片不是纯引用类型,而是聚合类型,例如这个结构:

type IntSlice struct {
ptr *int
len, cap int
}

So whenever a slice is passed by value a copy will be made of this structure, which is not the same as the one you passed.因此,每当按值传递切片时,都会为此结构制作一个副本,这与您传递的那个不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM