gpt4 book ai didi

go - Go 方法中的默认值

转载 作者:IT老高 更新时间:2023-10-28 12:58:38 24 4
gpt4 key购买 nike

有没有办法在 Go 的函数中指定默认值?我试图在文档中找到它,但我找不到任何说明这是可能的。

func SaySomething(i string = "Hello")(string){
...
}

最佳答案

否,但还有一些其他选项可以实现默认值。有一些good blog posts关于这个主题,但这里有一些具体的例子。

选项1:调用者选择使用默认值

// Both parameters are optional, use empty string for default value
func Concat1(a string, b int) string {
if a == "" {
a = "default-a"
}
if b == 0 {
b = 5
}

return fmt.Sprintf("%s%d", a, b)
}

选项 2:最后一个可选参数

// a is required, b is optional.
// Only the first value in b_optional will be used.
func Concat2(a string, b_optional ...int) string {
b := 5
if len(b_optional) > 0 {
b = b_optional[0]
}

return fmt.Sprintf("%s%d", a, b)
}

选项 3: 配置结构

// A declarative default value syntax
// Empty values will be replaced with defaults
type Parameters struct {
A string `default:"default-a"` // this only works with strings
B string // default is 5
}

func Concat3(prm Parameters) string {
typ := reflect.TypeOf(prm)

if prm.A == "" {
f, _ := typ.FieldByName("A")
prm.A = f.Tag.Get("default")
}

if prm.B == 0 {
prm.B = 5
}

return fmt.Sprintf("%s%d", prm.A, prm.B)
}

选项 4: 完整的可变参数解析(javascript 样式)

func Concat4(args ...interface{}) string {
a := "default-a"
b := 5

for _, arg := range args {
switch t := arg.(type) {
case string:
a = t
case int:
b = t
default:
panic("Unknown argument")
}
}

return fmt.Sprintf("%s%d", a, b)
}

关于go - Go 方法中的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19612449/

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