Dynamically append each values into 2D slice in GOLANG
我希望有一个这样的数据结构(数组或切片):
1 | [[a b c d e][f g h i j] [k l m n o] [p q r s t] [u v w x y]] |
这样a就是节点从"a"到"a"之间的距离。(应为0)B是节点之间从"A"到"B"的距离。C是节点之间从"A"到"C"的距离。
F是节点之间从"B"到"A"的距离。g是节点之间从"b"到"b"的距离。(应为0)h是节点之间从"b"到"c"的距离。
现在我已经创建了一个类似于:
在函数内的for循环中,我尝试动态填充此切片,如下所示:
1 | shortestPathSLice = append(shortestPathSLice[0][index], lowEstimate[0]) |
号
其中,lowestimate[0]是两个节点之间最小距离的值。
但是,我得到一个错误:附加的第一个参数必须是slice;has int
有人能告诉我如何在切片中的每个元素中动态附加值吗?
**代码**
1 2 3 4 5 6 7 8 9 10 11 12 | var shortestPathSLice = make([][]int, 5) for index := 0; index < len(t.Location_ids); index++ { lowEstimate := make([]int, len(priceestimatestruct.Prices)) for i := 0; i < len(priceestimatestruct.Prices); i++ { lowEstimate[i] = priceestimatestruct.Prices[i].LowEstimate } sort.Ints(lowEstimate) fmt.Println("LowEstimate array :", lowEstimate) shortestPathSLice[0] = make([]int, len(lowEstimate)) shortestPathSLice[0][index] = lowEstimate[0] } |
The Go Programming Language Specification
Appending to and copying slices
The built-in functions append and copy assist in common slice
operations. For both functions, the result is independent of whether
the memory referenced by the arguments overlaps.The variadic function append appends zero or more values x to s of
type S, which must be a slice type, and returns the resulting slice,
also of type S. The values x are passed to a parameter of type ...T
where T is the element type of S and the respective parameter passing
rules apply. As a special case, append also accepts a first argument
assignable to type []byte with a second argument of string type
followed by .... This form appends the bytes of the string.
1 append(s S, x ...T) S // T is the element type of SIf the capacity of s is not large enough to fit the additional values,
append allocates a new, sufficiently large underlying array that fits
both the existing slice elements and the additional values. Otherwise,
append re-uses the underlying array.
号
例如,使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package main import"fmt" func main() { { // using append dim := 5 matrix := make([][]int, dim) // dim*dim matrix for i := 0; i < dim; i++ { matrix[i] = make([]int, 0, dim) vector := make([]int, dim) for j := 0; j < dim; j++ { vector[j] = i*dim + j matrix[i] = append(matrix[i], vector[j]) } } fmt.Println(matrix) } { // using index dim := 5 matrix := make([][]int, dim) // dim*dim matrix for i := range matrix { matrix[i] = make([]int, dim) vector := make([]int, dim) for j := range matrix[i] { vector[j] = i*dim + j matrix[i][j] = vector[j] } } fmt.Println(matrix) } } |
输出:
1 2 | [[0 1 2 3 4] [5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]] [[0 1 2 3 4] [5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]] |
号