登录
首页 >  Golang >  Go问答

奇怪的切片行为

来源:stackoverflow

时间:2024-04-20 14:30:42 138浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《奇怪的切片行为》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我正在尝试实现 bfs 算法来查找图中的所有路径(从 src 和 dest)。我正在使用切片来模拟队列,但是当我在 for 循环中向切片追加多个元素时,切片会被损坏(追加未按预期工作)。我不知道为什么。我是 goland 的新人

// 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 需要两个参数,长度和(可选)容量:

make([]t, len, cap)

len 是它包含的元素的起始数量,capacity 是它在不扩展的情况下可以包含的元素数量。有关 A Tour of Go 的更多信息。

视觉上:

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 演示的链接:https://play.golang.org/p/ezoUGPHqSRj

理论要掌握,实操不能落!以上关于《奇怪的切片行为》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>