2023-06-01 07:00:00

Go?

Go可以有可选参数吗?或者我可以定义两个不同的函数,具有相同的名称和不同数量的参数?


当前回答

你可以使用指针,如果你不想使用它们,让它们为nil:

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)
}

其他回答

我最终使用了参数和可变参数结构的组合。这样,我就不需要改变现有的由多个服务使用的接口,而且我的服务能够根据需要传递额外的参数。golang playground中的示例代码:https://play.golang.org/p/G668FA97Nu

Go语言不支持方法重载,但你可以像可选参数一样使用可变参数,也可以使用interface{}作为参数,但这不是一个好的选择。

所以我觉得我来这个派对已经晚了,但我一直在寻找是否有比我现在做的更好的方法。这在某种程度上解决了你试图做的事情,同时也给出了一个可选参数的概念。

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"})
}

更新1:

添加了一个功能示例,以显示功能与示例的对比

您可以通过映射传递任意命名参数。如果参数具有不一致的类型,则必须使用“aType = map[key].(*foo.type)”断言类型。

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})
}

实现可选参数的一个好方法是使用可变参数。函数实际上接收您指定的任何类型的片。

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

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