Go 中 for-loop 之外未使用的变量

Unused variable outside of a for-loop in Go

我无法编译以下 Go 代码。我不断收到未使用变量 'header' 的错误消息。我正在尝试读取和处理 CSV 文件。该文件是逐行读取的,因此我需要将 header 保存到一个“outside-the-loop”变量中,以便在处理 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
        }
    }
}

您可以分配一个空白标识符来编译您的代码,例如:_ = 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