Here is my Go program:
package main
import (
"bufio"
"flag"
. "fmt"
"os"
)
var (
testBool *bool
myName *string
)
func main() {
testBool = flag.Bool("testbool", false, "test bool flag")
flag.Parse()
Println(*testBool)
funcFlags()
}
func funcFlags() {
reader := bufio.NewReader(os.Stdin)
Print("Enter your name: ")
*myName, _ = reader.ReadString('\n')
Println(myName)
}
Its execution ends up with a nil pointer dereference error as shown below:
▶ go run main.go -testbool
true
Enter you name: John
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x10acc9e]
goroutine 1 [running]:
main.funcFlags()
/Users/pantelis/Desktop/cli_testing/main.go:25 +0x1de
main.main()
/Users/pantelis/Desktop/cli_testing/main.go:19 +0x13b
exit status 2
Why the assignment
*myName, _ = reader.ReadString('\n')
errors out as above, while this one
testBool = flag.Bool("testbool", false, "test bool flag")
succeeds.
Both variables (i.e. testBool and myName) are initialised the same way.