-2

I didn't consider myself to be a newbie, but I can't figure out why this very simple code snippet fails to declare my integer.

func main () {

    var totalResults int

    rFile, err := os.Open("users.csv") //3 columns
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer rFile.Close()

    // Creating csv reader
    reader := csv.NewReader(rFile)

    lines, err := reader.ReadAll()
    if err == io.EOF {
        fmt.Println("Error:", err)
        return
    } else {

    }

    totalResults=len(lines)

}

It always says the value is not declared, this seems too simple.

I'm pretty sure it would work if I declared it using :=, but I wanted to declare everything at the top of the function.

michaelpri
  • 3,521
  • 4
  • 30
  • 46
user3888307
  • 2,825
  • 5
  • 22
  • 32
  • Why do you want to declare it at the top of the function? Generally most style guides for every c-ish language except JavaScript suggest declaring variables as close as possible to their point of use. Just say `var totalResults int = len(lines)`. – Jared Smith Jul 10 '17 at 00:05
  • I can't reproduce this error. – Adam Smith Jul 10 '17 at 00:07
  • 1
    In fact, the error I get with this code is that `totalResults` is declared and not used. Are you sure you're not misreading your error messages? – Adam Smith Jul 10 '17 at 00:09

1 Answers1

0

change your code:

lines, err := reader.ReadAll()
if err == io.EOF {
    fmt.Println("Error:", err)
    return
} else {

}

    totalResults=len(lines)

}

to:

    lines, err := reader.ReadAll()
if err == io.EOF {
    totalResults=len(lines)
} else {
    fmt.Println("Error:", err)
    return
}
    fmt.Println("total results:", totalResults)
}
Nevercare
  • 81
  • 3