John | 1 Aug 2012 03:51
Picon

Using structs as options args to function call, idiomatic question

I'm writing a pakcage that has a lot of function calls that accept a struct as optional arguments:


type Opt struct {
  Option1 string
  Option2 int32
}

func (o *Opt) getOption2() {
  if o.Option2 == nil {
    return 60
  }
  return o.Option2
}

func SomeFunc(args...., opt *Opt) {
...
}

For some of these, I have to have NewOpt(), because internally I may need to mark Option2 = -1 to know that I need to return a default value, because 0 is a valid value for that option(but I don't want it to be the default).

However, not all of my Opt structs that are passed need this.  Needing to use NewOpt() stinks, because you have to do this kind of stuff in your code:
o := NewOpt()
o.Option1 = "blah"

instead of:
&Opt{Option1: "blah"}

Is it idiomatic to have a mix of optional structs with NewOpt() and some without?  Is there a better way?

Gmane