我正在尝试实现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
}
答案 0 :(得分:-1)
您可能没有正确使用make
。切片的make
接受两个参数,长度和(可选)容量:
make([]T, len, cap)
Len是它包含的元素的起始数量,容量是它可以不扩展而可以包含的元素数量。有关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)
。
以下是前往“游乐场”的链接,其中显示了区别:https://play.golang.org/p/ezoUGPHqSRj