Weird Problem panic: runtime error: invalid memory address or nil pointer dereference

128 views
Skip to first unread message

virtue...@gmail.com

unread,
Jun 2, 2018, 6:58:04 PM6/2/18
to golang-nuts
I have simple go code as below, it returned the error as in " title " while executing, given the fact that /root/a.csv exists, and super user is executing go run a.go
Another problem is , if i removed println(fileInfo), it reported fileInfo declared and not used, am i not using it in the next line ? println(fileInfo.Size())??? This is very confusing 


package main


import(

"os"

)


func main() {

        var fileInfo os.FileInfo


        if fileInfo, err := os.Stat("/root/a.csv"); err != nil {

println(fileInfo)

        }

        println(fileInfo.Size())

        return

}


Shawn Milochik

unread,
Jun 2, 2018, 7:31:48 PM6/2/18
to golang-nuts
The problem is that fileInfo is being shadowed by the := syntax. Outside the "if" block, fileInfo is nil again. If you replace the := with = and add "var err error" above, it will work.

gp...@appliedgo.net

unread,
Jun 4, 2018, 1:17:46 AM6/4/18
to golang-nuts
In defense of the := syntax, the shorthand operator alone does not cause the problem, but only in combination with the if block creating a new scope. Try

    fileInfo, err := os.Stat("/...")
    if err != nil {

and the panic will also be gone. 
I never use the "if <assignment>; <condition>" syntax because I find it too convoluted. The shadowing problem is another good reason for not using that syntax.
Reply all
Reply to author
Forward
0 new messages