for-loopgovariablesunused-variables

Unused variable outside of a for-loop in Go


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
        }
    }
}

Solution

  • 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
    }
    

    https://go.dev/play/p/BrmYU2zAc9f