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

标签 c++ go idioms function-parameter

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

    相关文章:

    C++ : Using typedefs across multiple files in a namespace.

    GoLand,启动调试 session 时调试器挂起 Apple m1

    go - 使用neo4j驱动程序时使用match语句,返回的result.record为nil

    go - 构建用 go 编写的链代码时出错

    rust - 计数选项集合中出现次数的惯用方式

    c++ - 这种回调的使用是惯用的吗?

    inheritance - Golang 和继承

    c++ - MSVC : Using link. 手动执行

    c++ - 我可以将成员函数传递给 mu::Parser::DefineFun() 吗?

    c++ - 如何在openCV中将彩色图像转换为灰度图像?