我想知道 Go 中的最佳实践相当于使用默认参数绑定的 C++ 函数,这对于用户来说可能是最容易看到函数参数的(在 linter 帮助下)。
您认为最 GO 风格、最简单的测试功能使用方式是什么?
C++ 中的示例函数:
void test(int x, int y=0, color=Color());
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
亲:
缺点:
2. 带结构体参数:
type testOptions struct {
X int
Y int
color Color
}
func test(opt *testOptions)
// user
test(&testOptions{x: 5})
Run Code Online (Sandbox Code Playgroud)
亲:
缺点:
在模块github.com/cresty/defaults的帮助下,有一种方法可以设置默认值(但需要在运行时调用 Reflect 的成本)。
type …Run Code Online (Sandbox Code Playgroud)