ChatGPT解决这个技术问题 Extra ChatGPT

Optional Parameters in Go?

Can Go have optional parameters? Or can I just define two different functions with the same name and a different number of arguments?

Related: this is how it can be done to enforce mandatory parameters when using variadic as the optional parameters: Is it possible to trigger compile time error with custom library in golang?
Google made a terrible decision, because sometimes a function has a 90% use case and then a 10% use case. The optional arg is for that 10% use case. Sane defaults means less code, less code means more maintainability.
I think not having optional parameters is a good decision. I've seen optional parameters abused pretty severely in C++ -- 40+ arguments. It's very error-prone to count through the arguments and make sure you're specifying the right one, especially without named parameters. Much better to use a struct as mentioned by @deamon .
@Jonathan there are several ways to deal with this. One way is to pass a struct with all parameters for the function. This will have the added benefit of having named parameters (clearer than positional parameters) and all parameters which are not provided have their default value. And of course just creating a wrapper function, which passes the default value to the full function. e.g. Query and QueryWithContext
@Jonathan it doesn't seem to work out of the box in VS Code, Visual Studio, IntelliJ, atom or sublime. What IDE are you referring to, or are there extensions/settings which provide this ?

A
Andrew Hare

Go does not have optional parameters nor does it support method overloading:

Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.


Is make a special case, then? Or is it not even really implemented as a function…
@Mk12 make is a language construct and the rules mentioned above don't apply. See this related question.
Method overloads - A great idea in theory and excellent when implemented well. However I have witnessed rubbish indecipherable overloading in practice and would therefore agree with Google's decision
I'm going to go out on a limb and disagree with this choice. The language designers have basically said, "We need function overloading to design the language we want, so make, range and so on are essentially overloaded, but if you want function overloading to design the API you want, well, that's tough." The fact that some programmers misuse a language feature is not an argument for getting rid of the feature.
@Tom they consider function overloading abusive but goto's are just fine... (╯°□°)╯︵ ┻━┻
F
Ferguzz

A nice way to achieve something like optional parameters is to use variadic args. The function actually receives a slice of whatever type you specify.

func foo(params ...int) {
    fmt.Println(len(params))
}

func main() {
    foo()
    foo(1)
    foo(1,2,3)
}

in the above example, params is a slice of ints
But only for the same type of params :(
@JuandeParras Well, you can still use something like ...interface{} I guess.
With ...type you are not conveying the meaning of the individual options. Use a struct instead. ...type is handy for values that you would otherwise have to put in an array before the call.
this made me feel that a perfect language doesn't exist. loved everything about go, but this :(
d
deamon

You can use a struct which includes the parameters:

type Params struct {
  a, b, c int
}

func doIt(p Params) int {
  return p.a + p.b + p.c 
}

// you can call it without specifying all parameters
doIt(Params{a: 1, c: 9})

It would be great if structs could have default values here; anything the user omits is defaulted to the nil value for that type, which may or may not be a suitable default argument to the function.
@lytnus, I hate to split hairs, but fields for which values are omitted would default to the 'zero value' for their type; nil is a different animal. Should the type of the omitted field happen to be a pointer, the zero value would be nil.
@burfl yeah, except the notion of "zero value" is absolutely useless for int/float/string types, because those values are meaningful and so you can't tell the difference if the value was omitted from the struct or if zero value was passed intentionally.
@keymone, I don't disagree with you. I was merely being pedantic about the statement above that values omitted by the user default to the "nil value for that type", which is incorrect. They default to the zero value, which may or may not be nil, depending on whether the type is a pointer.
I feel that the fact that an option such as this needs to be considered and can be used highlights that it might be better to have optional and default parameters. At least if we have them then the purpose is clear instead of being concealed behind artificial constructs that obscure what developers intention is and which could themselves end up being misused beyond what they are intended for.
i
iliketocode

For arbitrary, potentially large number of optional parameters, a nice idiom is to use Functional options.

For your type Foobar, first write only one constructor:

func NewFoobar(options ...func(*Foobar) error) (*Foobar, error){
  fb := &Foobar{}
  // ... (write initializations with default values)...
  for _, op := range options{
    err := op(fb)
    if err != nil {
      return nil, err
    }
  }
  return fb, nil
}

where each option is a function which mutates the Foobar. Then provide convenient ways for your user to use or create standard options, for example :

func OptionReadonlyFlag(fb *Foobar) error {
  fb.mutable = false
  return nil
}

func OptionTemperature(t Celsius) func(*Foobar) error {
  return func(fb *Foobar) error {
    fb.temperature = t
    return nil
  }
}

Playground

For conciseness, you may give a name to the type of the options (Playground) :

type OptionFoobar func(*Foobar) error

If you need mandatory parameters, add them as first arguments of the constructor before the variadic options.

The main benefits of the Functional options idiom are :

your API can grow over time without breaking existing code, because the constuctor signature stays the same when new options are needed.

it enables the default use case to be its simplest: no arguments at all!

it provides fine control over the initialization of complex values.

This technique was coined by Rob Pike and also demonstrated by Dave Cheney.


Clever, but too complicated. The philosophy of Go is to write code in a straightforward way. Just pass a struct and test for default values.
Just FYI, the original author of this idiom, at at least the first publisher referenced, is Commander Rob Pike, whom I consider authoritative enough for Go philosophy. Link - commandcenter.blogspot.bg/2014/01/…. Also search for "Simple is complicated".
#JMTCW, but I find this approach very difficult to reason about. I would far prefer to pass in a struct of values, whose properties could be func()s if need be, than that bend my brain around this approach. Whenever I have to use this approach, such as with the Echo library, I find my brain getting caught in the rabbit hole of abstractions. #fwiw
this is such an amazing answer! Thanks a lot :)
p
peterSO

Neither optional parameters nor function overloading are supported in Go. Go does support a variable number of parameters: Passing arguments to ... parameters


J
Jonathan Leffler

No -- neither. Per the Go for C++ programmers docs,

Go does not support function overloading and does not support user defined operators.

I can't find an equally clear statement that optional parameters are unsupported, but they are not supported either.


"There is no current plan for this [optional parameters]." Ian Lance Taylor, Go language team. groups.google.com/group/golang-nuts/msg/030e63e7e681fd3e
No User defined operators is a terrible decision, as it is the core behind any slick math library, such as dot products or cross products for linear algebra, often used in 3D graphics.
Я
Ярослав Рахматуллин

You can pass arbitrary named parameters with a map. You will have to assert types with "aType = map[key].(*foo.type)" if the parameters have non-uniform types.

type varArgs map[string]interface{}

func myFunc(args varArgs) {

    arg1 := "default"
    if val, ok := args["arg1"]; ok {
        arg1 = val.(string)
    }

    arg2 := 123
    if val, ok := args["arg2"]; ok {
        arg2 = val.(int)
    }

    fmt.Println(arg1, arg2)
}

func Test_test() {
    myFunc(varArgs{"arg1": "value", "arg2": 1234})
}

Here's some commentary on this approach: reddit.com/r/golang/comments/546g4z/…
@ЯрославРахматуллин: It's a tutorial, not live code. Sometimes it's nice if things are explained.
A
Alexis Wilke

Go doesn’t support optional parameters , default values and function overloading but you can use some tricks to implement the same.

Sharing one example where you can have different number and type of arguments in one function. It’s a plain code for easy understanding you need to add error handling and some logic.

func student(StudentDetails ...interface{}) (name string, age int, area string) {
    age = 10 //Here Age and area are optional params set to default values
    area = "HillView Singapore"

    for index, val := range StudentDetails {
        switch index {
            case 0: //the first mandatory param
                name, _ = val.(string)
            case 1: // age is optional param
                age, _ = val.(int)
            case 2: //area is optional param
                area, _ = val.(string)
        }
    }
    return
}

func main() {
    fmt.Println(student("Aayansh"))
    fmt.Println(student("Aayansh", 11))
    fmt.Println(student("Aayansh", 15, "Bukit Gombak, Singapore"))
}

ugh, that is horrible.
M
Maxs728

So I feel like I'm way late to this party but I was searching to see if there was a better way to do this than what I already do. This kinda solves what you were trying to do while also giving the concept of an optional argument.

package main

import "fmt"

type FooOpts struct {
    // optional arguments
    Value string
}

func NewFoo(mandatory string) {
    NewFooWithOpts(mandatory, &FooOpts{})
}

func NewFooWithOpts(mandatory string, opts *FooOpts) {
    if (&opts) != nil {
        fmt.Println("Hello " + opts.Value)
    } else {
        fmt.Println("Hello")
    }
}

func main() {
    NewFoo("make it work please")

    NewFooWithOpts("Make it work please", &FooOpts{Value: " World"})
}

Update 1:

Added a functional example to show functionality versus the sample


I like this over the other alternatives. Also this is a pattern I've seen across many libraries, when something has different options and is going to be reusable you can create a struct to represent those options and pass the options by parameter, or you can nil the options to use defaults. Also the options can be documented in their own struct and you can create predefine sets of options. I've seen this in GitHub client library and go-cache library among others.
@madzohan please don't change my code example to fit your needs... you can request that the changes are made or provide your own sample below... Your example fundamentally changed the functionality of my example. A void function that does something does not need a return to suite your needs.
C
Clay Risser

You can encapsulate this quite nicely in a func similar to what is below.

package main

import (
        "bufio"
        "fmt"
        "os"
)

func main() {
        fmt.Println(prompt())
}

func prompt(params ...string) string {
        prompt := ": "
        if len(params) > 0 {
                prompt = params[0]
        }
        reader := bufio.NewReader(os.Stdin)
        fmt.Print(prompt)
        text, _ := reader.ReadString('\n')
        return text
}

In this example, the prompt by default has a colon and a space in front of it . . .

: 

. . . however you can override that by supplying a parameter to the prompt function.

prompt("Input here -> ")

This will result in a prompt like below.

Input here ->

B
BaSO4

Go language does not support method overloading, but you can use variadic args just like optional parameters, also you can use interface{} as parameter but it is not a good choice.


M
Malte

You could use pointers and leave them nil if you don't want to use them:

func getPosts(limit *int) {
  if optParam != nil {
    // fetch posts with limit 
  } else {
    // fetch all posts
  }
}

func main() {
  // get Posts, limit by 2
  limit := 2
  getPosts(&limit)

  // get all posts
  getPosts(nil)
}

Totally agree.Sometimes putting nil as parameter can be much simpler than additional changes.
Was looking to see if optional parameters or alternatively parameter default values could be done so this is possible; func (n *Note) save(extension string = ".txt") { ... } making ".txt" the default yet changeable extension of a file. Yet now am getting the idea this is just not the philosophy behind go and should just use separate Save() and SaveWithExtension(ext string) functions. Better to not fight it, doing so will just make everything harder in the long run.
Until you start using iota and "auto incremented" constants, in which case good luck with unadressable constants (because of course constants are magic and don't have a memory address)
A
Adriana

I ended up using a combination of a structure of params and variadic args. This way, I didn't have to change the existing interface which was consumed by several services and my service was able to pass additional params as needed. Sample code in golang playground: https://play.golang.org/p/G668FA97Nu


V
VinGarcia

I am a little late, but if you like fluent interface you might design your setters for chained calls like this:

type myType struct {
  s string
  a, b int
}

func New(s string, err *error) *myType {
  if s == "" {
    *err = errors.New(
      "Mandatory argument `s` must not be empty!")
  }
  return &myType{s: s}
}

func (this *myType) setA (a int, err *error) *myType {
  if *err == nil {
    if a == 42 {
      *err = errors.New("42 is not the answer!")
    } else {
      this.a = a
    }
  }
  return this
}

func (this *myType) setB (b int, _ *error) *myType {
  this.b = b
  return this
}

And then call it like this:

func main() {
  var err error = nil
  instance :=
    New("hello", &err).
    setA(1, &err).
    setB(2, &err)

  if err != nil {
    fmt.Println("Failed: ", err)
  } else {
    fmt.Println(instance)
  }
}

This is similar to the Functional options idiom presented on @Ripounet answer and enjoys the same benefits but has some drawbacks:

If an error occurs it will not abort immediately, thus, it would be slightly less efficient if you expect your constructor to report errors often. You'll have to spend a line declaring an err variable and zeroing it.

There is, however, a possible small advantage, this type of function calls should be easier for the compiler to inline but I am really not a specialist.


this is a builder pattern
Meh. What happens if A produces an error, but not B, C, D, and you don't care about A?
@ЯрославРахматуллин you could just separate the calls, e.g. build everything you care about first, then check the errors then set what you don't care to check. Or if you are the one writing the constructor in the first place you can just ignore the errors internally and not receive a *error for setting A.
u
user2133814

Another possibility would be to use a struct which with a field to indicate whether its valid. The null types from sql such as NullString are convenient. Its nice to not have to define your own type, but in case you need a custom data type you can always follow the same pattern. I think the optional-ness is clear from the function definition and there is minimal extra code or effort.

As an example:

func Foo(bar string, baz sql.NullString){
  if !baz.Valid {
        baz.String = "defaultValue"
  }
  // the rest of the implementation
}

this is not the point of the question, the problem still remains as you still need to call function with nil/default structure as second parameter.