【发布时间】:2021-11-14 20:22:04
【问题描述】:
我想知道 Go 中等效于使用默认参数绑定的 C++ 函数的最佳实践,这对于用户来说可能最容易看到函数参数(在 linter 的帮助下)。
您认为最 GO 风格和最简单的测试功能使用方式是什么?
C++ 中的示例函数:
void test(int x, int y=0, color=Color());
Go 中的等价性
1.具有多个签名:
func test(x int)
func testWithY(x int, y int)
func testWithColor(x int, color Color)
func testWithYColor(x int, y int, color Color)
专业人士:
- linter 将显示测试的所有可能性
- 编译器将采用最短路径
缺点:
- 当有很多参数时可能会不堪重负
2。带结构参数:
type testOptions struct {
X int
Y int
color Color
}
func test(opt *testOptions)
// user
test(&testOptions{x: 5})
专业人士:
- 只有一个签名
- 只能指定一些值
缺点:
- 需要定义一个结构体
- 这些值将由系统默认设置
借助模块github.com/creasty/defaults,可以设置默认值(但需要在运行时调用反射)。
type testOptions struct {
X int
Y int `default:"10"`
color Color `default:"{}"`
}
func test(opt *testOptions) *hg.Node {
if err := defaults.Set(opt); err != nil {
panic(err)
}
}
专业人士:
- 设置默认值
缺点:
- 在运行时使用反射
附:
我看到了使用可变参数... 或/与interface{},但我发现要知道使用哪些参数并不容易(或者也许有一种方法可以向 linter 指示参数列表)。
【问题讨论】:
-
要添加另一个选项,您可能对Builder pattern 感兴趣。这是一篇解释 Go 中可能实现的帖子:devcharmander.medium.com/…
标签: c++ go idioms function-parameter