gpt4 book ai didi

c++ - Golang 替代 C++ 函数,默认参数为 : multiple functions, 或结构参数

转载 作者:行者123 更新时间:2023-12-04 15:56:39 24 4
gpt4 key购买 nike

我想知道 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)
亲:
  • 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)
    }
    }
    亲:
  • 设置默认值

  • 缺点:
  • 在运行时使用反射

  • 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com