我正在尝试实现 BFS 算法以查找图中的所有路径(来自 src 和 dest)。我正在使用一个 slice 来模拟一个队列,但是当我在 for 循环中向它追加多个元素时,该 slice 会损坏(追加没有按预期工作)。我不知道为什么。我是 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
。 slice 的 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)
您正在创建一定长度的 slice ,然后附加到末尾,这意味着 slice 的前 N 个元素是零值。将您的 make([]T, N)
更改为 make([]T, 0, N)
。
这是一个显示不同之处的 Go Playground 链接:https://play.golang.org/p/ezoUGPHqSRj
关于go - 奇怪的 slice 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57359428/