I've started looking at Golang, and following an example to pass in command line arguments, I've got this code:
package main
import (
"flag"
"fmt"
)
func main() {
wordPtr := flag.String("namestring", "stringvalue", "Pass in a string")
numPtr := flag.Int("number", 11, "Pass in an int")
boolPtr := flag.Bool("switchflag", false, "Pass in a bool")
var svar string
flag.StringVar(&svar, "svar", "svarstringvalue", "A string variable")
flag.Parse()
fmt.Println("Word:", *wordPtr)
fmt.Println("Word2:", wordPtr)
fmt.Println("numb:", *numPtr)
fmt.Println("numb2", numPtr)
fmt.Println("switchflag", *boolPtr)
fmt.Println("switchflag2", boolPtr)
fmt.Println("svar:", svar)
fmt.Println("svar2", &svar)
fmt.Println("svar3", *svar) //<-- This won't work...
fmt.Println("tail:", flag.Args())
}
My question is, why do I get the value of the other pointers if I dereference it (like *wordPtr
etc), whereas if I pass wordPtr
in, I get the memory address, but with svar
, I have to pass in svar
to get the value, and &svar
gets me the memory address?
Looking at the documentation here https://golang.org/pkg/flag/, it says that you pass in a variable to store the flag (presumably a variable that is already created?), but I still don't understand why I have to do something different to it to get the value, when compared with other variables.
This is the result of me running it with passing in some commands:
➜ Documents go run main.go -number 42 -switchflag -svar testtringvalue
Word: stringvalue
Word2: 0xc42005c1e0
numb: 42
numb2 0xc4200160a0
switchflag true
switchflag2 0xc4200160a8
svar: testtringvalue
svar2 0xc42005c1f0
tail: []
Any help is appreciated. Also, if I've got any understanding of it wrong, please let me know.
Cheers.