【问题标题】:Go: Append byte slices in a loop [duplicate]Go:在循环中附加字节切片[重复]
【发布时间】:2015-11-05 05:19:25
【问题描述】:

我是 Go 新手,所以如果这个问题已经得到解答,我深表歉意,我正在尝试在 Go 中附加一个字节切片,但我没有找到解决方案的运气。我需要拆分文件的第一行,我已经完成了;并将其余部分写入字节片以在事后进行解析。到目前为止,代码如下所示:

// Here we extract the first line to name our title and category
var title, category string
var content []byte
in, err := os.Open(file)
utils.CheckErr(err, "could not open file: "+file)
defer in.Close()
// open file
scanner := bufio.NewScanner(in)
lineCount := 1
for scanner.Scan() {
    if lineCount == 1 {
        // assign title and category
        splitString := strings.Split(scanner.Text(), "::")
        title = splitString[0]
        category = splitString[1]
        fmt.Println("title: " + title + "category" + category) // usage to prevent compiler whine
    } else {
        // push the rest into an array to be parsed as jade
        line := scanner.Bytes()
        content = append(content, line) // The question is what goes here?
    }
    lineCount++
}

我尝试过使用 append 但这只会给我一个错误 不能在追加中使用 line (type []byte) 作为类型 byte

【问题讨论】:

    标签: arrays go


    【解决方案1】:

    我相信您只是在寻找; content = append(content, line...)

    【讨论】:

    • 啊哈!谢谢,好像已经搞定了:)
    • @Nick np。顺便说一句,这方面的文档在这里; golang.org/pkg/builtin/#append
    • 现在看它似乎很明显,但不知何故我就是不明白。谢谢大家,你真棒:)
    【解决方案2】:

    https://golang.org/ref/spec#Appending_and_copying_slices

    可能有重复,但直到我找到它...

    您的问题通过在line 的末尾添加“...”得到解决,如下所示:

    content = append(content, line...)
    

    【讨论】:

      猜你喜欢
      • 2018-05-03
      • 2016-06-04
      • 1970-01-01
      • 2018-12-05
      • 2019-07-26
      • 2016-07-03
      • 2020-03-26
      • 2018-12-20
      • 1970-01-01
      相关资源
      最近更新 更多