Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading