Home > Net >  Golang cannot obain the function return values via pointers
Golang cannot obain the function return values via pointers

Time:09-24

Why can't I use the points types of return values like this?

// test.go
nReq := *flag.Int("n", 10000, "set total requests")
flag.Parse()
fmt.Println(nReq)

// test -n 200
10000
// the value is still 10000.

It always returns the default value(10000).
I need to use:

nReq := flag.Int("n", 10000, "set total requests")
flag.Parse()
fmt.Println(*nReq)

// test -n 200
200
// the value is updated to the new flag(200)

CodePudding user response:

flag.Int() does not parse the flag "immediately", it just returns a pointer to a variable where the flag value will be stored when parsed.

So you if you dereference it right away, you'll just get the default value you provided. You have to call flag.Parse().

If you don't want to work with pointers, declare the variable prior, and use flag.IntVar(), for example:

var nReq int
flag.IntVar(&nReq, "n", 10000, "set total requests")
flag.Parse()
fmt.Println(nReq)

Now nReq is not a pointer, you may use it without having to dereference all the time.

  • Related