Skip to content

Conversation

@MichaelMure
Copy link

This is a POC that it's possible to relax the constraint.Integer constraint into simply constraint.Ordered. This means in particular that string enum can be accepted, which I found to be a common case.

It seems to work, but I may not have covered all the cases properly.

This is a POC that it's possible to relax the `constraint.Integer` constraint into simply `constraint.Ordered`. This means in particular that string enum can be accepted, which I found to be a common case.

It seems to work, but I may not have covered all the cases properly.

Signed-off-by: Michael Muré <batolettre@gmail.com>
@thediveo
Copy link
Owner

Thank you very much for catching this and contributing this improvement! I will later cross-check just in case, but this is definitely good to have. How to you use it with strings? I'm wondering if defining our own constraint type from basically constraint.Integer | ~string might be more precise or whether float has usecases...?

@MichaelMure
Copy link
Author

MichaelMure commented Dec 17, 2025

Really like you would expect:

type Sample string

const (
	SampleInuseSpace   Sample = "inuse_space"
	SampleInuseObjects        = "inuse_objects"
	SampleAllocSpace          = "alloc_space"
	SampleAllocObjects        = "alloc_objects"
)

// ------

var allocSampleIds = map[engine.Sample][]string{
	engine.SampleInuseSpace:   {"inuse_space"},
	engine.SampleInuseObjects: {"inuse_objects"},
	engine.SampleAllocSpace:   {"alloc_space"},
	engine.SampleAllocObjects: {"alloc_objects"},
}

var allocSampleHelp = map[engine.Sample]string{
	engine.SampleInuseSpace:   "Memory in use (space)",
	engine.SampleInuseObjects: "Memory in use (objects)",
	engine.SampleAllocSpace:   "Memory allocated (space)",
	engine.SampleAllocObjects: "Memory allocated (objects)",
}

sampleEnum := enumflag.New(&options.sample, "sample", allocSampleIds, enumflag.EnumCaseInsensitive)
flags.VarP(sampleEnum, "sample", "s", "Memory sample to analyse")
err := sampleEnum.RegisterCompletion(cmd, "sample", allocSampleHelp)

Btw, it would be really nice to have a function to generate the description of possible values (something like inuse_space, inuse_objects, alloc_space, alloc_objects in this case), to easily put into the flag description.

As for the constraint, I don't think it makes sense to define a custom one. As I understand, your only imperative is Ordered as you are using a map somewhere. You don't need to restrict what is possible. Besides strings, IMHO it would be equally valid to use any type that makes sense in the final app, as long as it works with your code.

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

Successfully merging this pull request may close these issues.

2 participants