【问题标题】:Golang prepend the array [duplicate]Golang在数组前面添加[重复]
【发布时间】:2018-11-15 00:43:12
【问题描述】:
package main

import (
    "fmt"
)

func main() {

    var result [][]int
    var tempArr []int
    tempArr = append(tempArr, 1, 2, 3, 5)
    result = append(result, tempArr)
    prepend := []int{1, 2, 3}
    result = append([]int{prepend}, result...) // Not working
    fmt.Println(result)
}

添加到数组的正确方法是什么?我需要帮助来修复这条线:

result = append([]int{prepend}, result...)

【问题讨论】:

  • 在切片技巧 wiki 中的 push front 之后,代码应为:result = append([][]int{prepend}, result...)
  • 我通过这样做 result = append([][]int{prepend}, result...) 得到了这个工作

标签: go


【解决方案1】:

类型不匹配。 []int{prepend} 类型为 [] int。但是prepend 类型是[] int。所以[]int{prepend} 不正确。正确的方法是[][]int{prepend},下面的代码会通过。

result = append([][]int{prepend}, result...)

结果将是:

[[1 2 3] [1 2 3 5]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-06
    • 2013-09-13
    • 2020-01-26
    • 2019-03-08
    • 1970-01-01
    • 2016-12-24
    • 2019-11-05
    • 1970-01-01
    相关资源
    最近更新 更多