go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -


i implementing go program uses bufio.scanner , bufio.writer have packaged code follows

package main  import (     "fmt"     "player/command"     "strings" )  func main() {     //enter code here. read input stdin. print output stdout        commands.scanner.scan() {          //scan new line , send comand variable check command exist or not         input := strings.split(strings.trim(commands.scanner.text(), " "), " ")         command := input[0]          if command == "" {             fmt.printf("$ %s:", commands.pwd)             continue         }          if !commands.commands[command] {             commands.throwerror("cannot recognize input.")          } else {              commands.execute(command, input[1:], nil)          }         fmt.printf("$ %s:", commands.pwd)     } } 

i using init.go file in main package follows

package main  import (     "flag"     "player/source" )  func init() {     sourceflag := flag.string("filename", "", "if input through source file")     flag.parse()     if *sourceflag != "" {         source.input(*sourceflag)     } } 

and final package player/source follows :-

package source      import (         "bufio"         "log"         "os"         "player/command"     )      func input(source string) {         if source != "" {             readfile, err := os.openfile(source, os.o_rdonly, os.modeexclusive)             if err != nil {                 log.fatal(err)             }             commands.scanner = bufio.newscanner(readfile)             writefile, err := os.create(source + "_output.txt")             if err != nil {                 log.fatal(err)             }             commands.writer = bufio.newwriter(writefile)         } else {             commands.scanner = bufio.newscanner(os.stdin)             commands.writer = bufio.newwriter(os.stdout)             // fmt.println(commands.scanner)         }     } 

execution of code results in

panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0x1 addr=0x58 pc=0x4a253a]  goroutine 1 [running]: bufio.(*scanner).scan(0x0, 0x5)     /usr/local/go/src/bufio/scan.go:120 +0x2a main.main()     /home/xyz/dev/go/src/players/main.go:13 +0x124 

i dont know reason after initializing scanner why not been able read it

one reason why command.scanner not initialized not passing filename argument main script. in case, source.input(*sourceflag) never called, per if condition (if *sourceflag != "" false in case of missing filename option).

also, since checking empty file name later in source, condition in main's init redundant. try:

func init() {     sourceflag := flag.string("filename", "", "if input through source file")     flag.parse()     source.input(*sourceflag) } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

c - double free or corruption (fasttop) -