小编Sco*_*s S的帖子

Golang 替代带有默认参数的 C++ 函数:多个函数或结构参数

我想知道 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)

亲:

  • linter 将显示测试的所有可能性
  • 编译器会选择最短路径

缺点:

  • 当参数很多时可能会不知所措

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)

c++ idioms go function-parameter

2
推荐指数
1
解决办法
512
查看次数

标签 统计

c++ ×1

function-parameter ×1

go ×1

idioms ×1