英文:
Unused variable outside of a for-loop in Go
问题
我无法编译以下Go代码。我一直收到一个错误,说变量'header'未被使用。我正在尝试读取和处理一个CSV文件。文件逐行读取,所以我需要将标题保存到一个“循环外”的变量中,以便在处理CSV行时可以引用它。有人知道我作为一个新的Go用户做错了什么吗?
func main() {
...
inputData := csv.NewReader(file)
var header []string
//keep reading the file until EOF is reached
for j := 0; ; j++ {
i, err := inputData.Read()
if err == io.EOF {
break
}
if j == 0 {
header = i
} else {
// Business logic in here
fmt.Println(i)
//TODO convert to JSON
//TODO send to SQS
}
}
}
以下是翻译好的代码:
func main() {
...
inputData := csv.NewReader(file)
var header []string
// 读取文件直到达到EOF
for j := 0; ; j++ {
i, err := inputData.Read()
if err == io.EOF {
break
}
if j == 0 {
header = i
} else {
// 在这里处理业务逻辑
fmt.Println(i)
//TODO 转换为JSON
//TODO 发送到SQS
}
}
}
英文:
I can't compile the following Go code. I keep getting an error that variable 'header' is not used. I'm trying to read and process a CSV file. The file is read line by line an so I need to save the header into a "outside-the-loop" variable I can refer to when processing CSV lines. Anyone knows what I'm doing incorrectly as a new Go user?
func main() {
...
inputData := csv.NewReader(file)
var header []string
//keep reading the file until EOF is reached
for j := 0; ; j++ {
i, err := inputData.Read()
if err == io.EOF {
break
}
if j == 0 {
header = i
} else {
// Business logic in here
fmt.Println(i)
//TODO convert to JSON
//TODO send to SQS
}
}
}
答案1
得分: 2
你可以将一个空标识符赋值给变量,只是为了能够编译你的代码,例如:_ = header
。以下是一个示例:
package main
import (
"encoding/csv"
"fmt"
"io"
"strings"
)
func main() {
in := `first_name,last_name,username
"Rob","Pike",rob
Ken,Thompson,ken
"Robert","Griesemer","gri"
`
file := strings.NewReader(in)
inputData := csv.NewReader(file)
var header []string
//keep reading the file until EOF is reached
for j := 0; ; j++ {
i, err := inputData.Read()
if err == io.EOF {
break
}
if j == 0 {
header = i
} else {
// Business logic in here
fmt.Println(i)
//TODO convert to JSON
//TODO send to SQS
}
}
_ = header
}
你可以在这里运行这段代码:https://go.dev/play/p/BrmYU2zAc9f
英文:
You can assign to a blank identifier just to be able to compile your code, like: _ = header
. As example:
package main
import (
"encoding/csv"
"fmt"
"io"
"strings"
)
func main() {
in := `first_name,last_name,username
"Rob","Pike",rob
Ken,Thompson,ken
"Robert","Griesemer","gri"
`
file := strings.NewReader(in)
inputData := csv.NewReader(file)
var header []string
//keep reading the file until EOF is reached
for j := 0; ; j++ {
i, err := inputData.Read()
if err == io.EOF {
break
}
if j == 0 {
header = i
} else {
// Business logic in here
fmt.Println(i)
//TODO convert to JSON
//TODO send to SQS
}
}
_ = header
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论