英文:
Go: Append byte slices in a loop
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我刚开始学习Go语言,如果这个问题已经有答案了,我很抱歉。我正在尝试在Go中追加一个字节切片,但是我找不到解决方案。我需要将文件的第一行分离出来,这一步我已经完成;然后将剩余部分写入一个字节切片,以便稍后解析。到目前为止,代码看起来是这样的:
// 这里我们提取第一行作为标题和类别
var title, category string
var content []byte
in, err := os.Open(file)
utils.CheckErr(err, "无法打开文件:"+file)
defer in.Close()
// 打开文件
scanner := bufio.NewScanner(in)
lineCount := 1
for scanner.Scan() {
if lineCount == 1 {
// 分配标题和类别
splitString := strings.Split(scanner.Text(), "::")
title = splitString[0]
category = splitString[1]
fmt.Println("标题:" + title + " 类别:" + category) // 用于防止编译器报错
} else {
// 将剩余部分追加到切片中,以便解析为Jade格式
line := scanner.Bytes()
content = append(content, line...) // 问题是这里应该填什么?
}
lineCount++
}
我尝试使用append函数,但是它给出了以下错误:
cannot use line (type []byte) as type byte in append
英文:
I'm new to Go, so I apologise if this has already been answered, I'm trying to append a byte slice in Go and I am not having any luck finding a solution. I need to split off the first line of the file, which I've done; And write the rest into a byte slice to be parsed after the fact. So far the code looks like this:
// 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++
}
I've tried using append but that only gives me the error that
cannot use line (type []byte) as type byte in append
答案1
得分: 2
我相信你只是在寻找这样的代码:content = append(content, line...)
英文:
I believe you're simply looking for; content = append(content, line...)
答案2
得分: 2
请参考 https://golang.org/ref/spec#Appending_and_copying_slices
可能有重复的问题,但在我找到之前...
通过在line
的末尾添加"..."来解决您的问题,使其看起来像这样:
content = append(content, line...)
英文:
See https://golang.org/ref/spec#Appending_and_copying_slices
There is probably a duplicate but until I find it...
Your problem is solved by adding "..." to the end of line
so it looks like:
content = append(content, line...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论