Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Positional argument before positional,required argument doesn't work #124

Closed
Keithcat1 opened this issue Sep 23, 2020 · 5 comments
Closed

Comments

@Keithcat1
Copy link

Keithcat1 commented Sep 23, 2020

I have the following code:

package main
import(
	"github.com/alexflint/go-arg"
)
type args struct {
	Name string `arg:"positional"`
	Age int `arg:"positional,required"`
}

func main() {
	a:=args{}
	arg.MustParse(&a)
}

This is a weird example, but it shows what I'd like to do.
When I run "./cli 15", I want it to leave name alone and set age to 15, but it seems to assume that I passed in the value for name, because I get this:
Usage: cli NAME AGE
error: age is required

@atc0005
Copy link

atc0005 commented Sep 23, 2020

Try this:

// ...
type args struct {
        Age int `arg:"positional,required"`
        Name string `arg:"positional"`
}
// ...

@Keithcat1
Copy link
Author

Sorry, I should be more clear on what I want to have happend:
When I run "./cli 15", I want it to set age to 15 and leave name alone, and when I run "./cli "Me" 15" I want it to set Name to "Me" and Age to 15.
Now that I think about it, I could maybe do this with a []string slice, but that's kind of clunky.

@atc0005
Copy link

atc0005 commented Sep 27, 2020

When I run "./cli 15", I want it to set age to 15 and leave name alone, and when I run "./cli "Me" 15" I want it to set Name to "Me" and Age to 15.

Ah, I've not used this package for that specific use case, so unfortunately I have no advice there.

@alexflint
Copy link
Owner

You would have to do something like this:

var args struct {
  First *string `arg:"positional,required"
  Second *string `arg:"positional"`
}
arg.MustParse(&args)
var name string
var age int
if args.Second == nil {
  age = strconv.Atoi(*args.First)
} else {
  name = *args.First
  age = strconv.Atoi(*args.Second)
}

@alexflint
Copy link
Owner

Closing for now but feel free to reopen if you have further questions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants