Go 奇怪的切片行为

Go 奇怪的切片行为,go,slice,Go,Slice,我正在尝试实现BFS算法来查找图中的所有路径(从src和dest)。我使用一个切片来模拟队列,但是当我在for循环中将多个元素追加到切片时,该切片会损坏(追加没有按预期工作)。我不知道为什么。我刚来高兰德 // GetPathsFromCache retrieve information from loaded jsons in the cache func (cache *ModelsDataCache) GetPathsFromCache(modelUrn, selectedElement,

我正在尝试实现BFS算法来查找图中的所有路径(从src和dest)。我使用一个切片来模拟队列,但是当我在for循环中将多个元素追加到切片时,该切片会损坏(追加没有按预期工作)。我不知道为什么。我刚来高兰德

// GetPathsFromCache retrieve information from loaded jsons in the cache
func (cache *ModelsDataCache) GetPathsFromCache(modelUrn, selectedElement, targetType, authToken string, modelJSONs *ModelJSONs) []systemdetection.GraphPath {

    result := make([]systemdetection.GraphPath, 0)

    //create the queue which stores the paths
    q := make([]Path, 0)

    //Path to store the current path
    var currentPath Path
    currentPath.path = append(currentPath.path, selectedElement)
    q = append(q, currentPath)


    for len(q) > 0 {


        currentPath = q[0] //get top
        q = q[1:]


        lastInThePath := currentPath.path[len(currentPath.path)-1]
        connectedToTheCurrent := cache.GetConnectionsFromCache(modelUrn, lastInThePath, authToken, modelJSONs)

        lastInPathType := modelJSONs.Elements[lastInThePath].Type

        if lastInPathType == targetType {
            //cache.savePath(currentPath, &result)

            var newPath systemdetection.GraphPath
            newPath.Target = lastInThePath
            newPath.Path = currentPath.path[:]
            newPath.Distance = 666
            result = append(result, newPath)
        }


        for _, connected := range connectedToTheCurrent {
            if cache.isNotVisited(connected, currentPath.path) {


                var newPathN Path

                newPathN.path = currentPath.path
                newPathN.path = append(newPathN.path, connected)

                q = append(q, newPathN)
            }
        }

    }

    return result

}

您可能没有正确使用
make
<代码>生成对于一个片,有两个参数,长度和(可选)容量:

make([]T, len, cap)
Len是它包含的元素的起始数量,capacity是它可以包含而不扩展的元素数量。更多关于

视觉上:

make([]string, 5) #=> ["", "", "", "", ""]
make([]string, 0, 5) #=> [] (but the underlying array can hold 5 elements)
append
添加到数组的末尾,因此遵循相同的示例:

arr1 := make([]string, 5) #=> ["", "", "", "", ""]
arr1 = append(arr1, "foo") #=> ["", "", "", "", "", "foo"] 

arr2 := make([]string, 0, 5) #=> []
arr2 = append(arr2, "foo") #=> ["foo"] (underlying array can hold 4 more elements before expanding)
您正在创建一段长度的切片,然后将其追加到末尾,这意味着切片的前N个元素为零值。将
make([]T,N)
更改为
make([]T,0,N)


这里有一个指向Go Playerd的链接,显示了不同之处:

这段代码充满了调试语句,缺少足够的上下文来实际运行它。你能试着更新引用的代码以提供一个新代码吗?你说的“附加没有按预期工作”是什么意思?你期望得到什么样的结果?你得到了什么样的实际结果?好吧,就在我创建newPathN变量之前,我记录了队列的内容,在我添加之前,我发现最后几个元素不是它们应该的样子。实际上解决我的问题的方法是将“newPathN.path=currentPath.path”替换为第二个元素上的迭代,并在元素之后追加元素。我是go lang的新手,但我想问题在于我对队列的重新切片……我看到的两个
make
s都是
make(T,0)
,如果它们有容量会更好,但这不是“绝对的bug”。如果0实际上是0,是的。然而,考虑到编辑的数量,我认为假设OP的代码与当前编写的代码完全相同是不公平的。