2023-06-01 07:00:00

Go?

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


当前回答

你可以使用一个包含形参的结构体:

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

与省略号(params…SomeType)相比,其主要优点是可以将param结构体与不同的形参类型一起使用。

其他回答

不——都不是。根据Go for c++程序员文档,

Go不支持函数 重载,不支持用户 定义操作符。

我找不到一个同样明确的声明,说明可选参数不受支持,但它们也不受支持。

Go中不支持可选参数和函数重载。Go确实支持可变数量的参数:参数

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

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

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

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

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:

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

你可以使用指针,如果你不想使用它们,让它们为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)
}