3 ms·
I just solved a similar problem in a slower but fairly general way. It's not appropriate everywhere, but it works well for the use-case I built it for. I can't
by nknighthb 13y ago
I just solved a similar problem in a slower but fairly general way. It's not appropriate everywhere, but it works well for the use-case I built it for.
I can't share the actual code, unfortunately, but by using struct field tags, reflect, and json, you can end up with code that looks something like this:
type FArgs struct {
A int `def:"11"`
B string `def:"\"some default\""`
}
func f(margs map[string]interface{}) {
var args FArgs
SetupArgs(margs, &args)
// ...
}
If f() is being called in a tight loop, your overhead can be enormous, but outside performance-critical code, it's probably good enough.
- fauigerzigerk 13y agoYou're not just losing performance but also static type checking.
- nknighthb 13y agoNot really. If the passed-in or default value doesn't convert to the field's type, SetupArgs panics. Edit: Variations on this that offer compile-time type checking of passed-in values are possible, too. My use case wouldn't work well with that, though, because the function needs to be called by other functions that would have no clue about the FArgs struct. You could instead do a version that just swaps in a default for any nil fields. And in any case, you've got a lot more safety than the original Python code, no?
- fauigerzigerk 13y ago"And in any case, you've got a lot more safety than the original Python code, no?" Only insofar as your approach puts the values back into a struct that can subsequently be used in a type safe manner. Arguably that's better than having no type safety at all. But I think my main gripe with your design is that it is not just less type safe and slower, it also comes with more mental friction and verbosity than what Python does. Granted, it's a lot less verbose than my Go code, which makes it a good solution in some scenarios. But in my view it's not a good general replacement for default keyword args and you didn't claim it was.
- nknighthb 13y agoI certainly wasn't arguing it was a perfect substitute for default args, just that it was easier to manage than the example you gave. The application I'm currently working on is mostly a direct port of Python code to Go. Python code I originally wrote. You needn't tell me it fails to accomplish all the things Python's default args do.