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?
Vanja Pejovic | 1 Aug 2012 04:22
Picon

Re: Using structs as options args to function call, idiomatic question

How about something like this: http://play.golang.org/p/-TWc9zXsUK


If you give us some examples of what the functions are and what the option structs are, maybe we can give you a different way of doing whatever you're trying to do.

On Tue, Jul 31, 2012 at 9:51 PM, John <johnsiilver-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
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