constructor - Go 结构构造函数中具有默认值的可选参数

标签 constructor go default

我发现自己使用以下模式作为在 Go 结构构造函数中获取具有默认值的可选参数的方法:

package main

import (
    "fmt"
)

type Object struct {
    Type int
    Name string
}

func NewObject(obj *Object) *Object {
    if obj == nil {
        obj = &Object{}
    }
    // Type has a default of 1
    if obj.Type == 0 {
        obj.Type = 1
    }
    return obj
}

func main() {
    // create object with Name="foo" and Type=1
    obj1 := NewObject(&Object{Name: "foo"})
    fmt.Println(obj1)

    // create object with Name="" and Type=1
    obj2 := NewObject(nil)
    fmt.Println(obj2)

    // create object with Name="bar" and Type=2
    obj3 := NewObject(&Object{Type: 2, Name: "foo"})
    fmt.Println(obj3)
}

是否有更好的方法允许使用默认值的可选参数?

最佳答案

Dave Cheney 提供了一个很好的解决方案,您可以使用功能选项来覆盖默认值:

https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis

所以你的代码会变成:

package main

import (
    "fmt"
)

type Object struct {
    Type int
    Name string
}

func NewObject(options ...func(*Object)) *Object {
    // Setup object with defaults 
    obj := &Object{Type: 1}
    // Apply options if there are any
    for _, option := range options {
        option(obj)
    }
    return obj
}

func WithName(name string) func(*Object) {
    return func(obj *Object) {
        obj.Name = name
    }
}

func WithType(newType int) func(*Object) {
    return func(obj *Object) {
        obj.Type = newType
    }
}

func main() {
    // create object with Name="foo" and Type=1
    obj1 := NewObject(WithName("foo"))
    fmt.Println(obj1)

    // create object with Name="" and Type=1
    obj2 := NewObject()
    fmt.Println(obj2)

    // create object with Name="bar" and Type=2
    obj3 := NewObject(WithType(2), WithName("foo"))
    fmt.Println(obj3)
}

https://play.golang.org/p/pGi90d1eI52

关于constructor - Go 结构构造函数中具有默认值的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20150628/

相关文章:

mongodb - 官方 mongo-go-driver 的 UpdateOne 中 $set 的 bson 语法是什么

docker - 如何更改docker的默认容器名称和主机别名?

java - 如何打印对象的默认值?

C++11:未触发 move 构造函数

go - Golang 的 Homebrew 公式

java - 初始化列表的构造函数时出现 StackOverFlowError

c++ - 为什么我的 Go 解决方案给出的结果与 C++ 不同?

c++ - += 运算符在 C++ 中是如何实现的?

c++ - 映射构造函数如何以类比较的形式使用?

c++ - C++ 构造函数的问题