我想知道 Go 中的最佳实践,相当于使用默认参数绑定(bind) 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)
亲:缺点:
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)
}
}
亲:缺点:
PS:
我看到了使用可变参数
...
或/与 interface{}
但我发现要知道要使用哪些参数并不容易(或者可能有一种方法可以将参数列表指示给 linter)。
最佳答案
无论哪种方式都可以正常工作,但在 Go 中 functional options pattern实现此类功能可能更惯用。
它基于接受可变数量的 WithXXX 类型的函数参数的想法,这些参数扩展或修改调用的行为。
type Test struct {
X int
Y int
color Color
}
type TestOption func(*Test)
func test(x int, opts ...TestOption) {
p := &Test{
X: x,
Y: 12,
Color: defaultColor,
}
for _, opt := range opts {
opt(p)
}
p.runTest()
}
func main() {
test(12)
test(12, WithY(34))
test(12, WithY(34), WithColor(Color{1, 2, 3}))
}
func WithY(y int) TestOption {
return func(p *Test) {
p.Y = y
}
}
func WithColor(c Color) TestOption {
return func(p *Test) {
p.color = c
}
}
关于c++ - Golang 替代 C++ 函数,默认参数为 : multiple functions, 或结构参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69266062/