有没有办法在 Go 的函数中指定默认值?我试图在文档中找到它,但我找不到任何指定这甚至是可能的东西。
func SaySomething(i string = "Hello")(string){
...
}
原文由 denniss 发布,翻译遵循 CC BY-SA 4.0 许可协议
有没有办法在 Go 的函数中指定默认值?我试图在文档中找到它,但我找不到任何指定这甚至是可能的东西。
func SaySomething(i string = "Hello")(string){
...
}
原文由 denniss 发布,翻译遵循 CC BY-SA 4.0 许可协议
不,但是还有一些其他选项可以实现默认值。关于这个主题有一些 很好的博客文章,但这里有一些具体的例子。
选项 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)
}
原文由 headmaster 发布,翻译遵循 CC BY-SA 4.0 许可协议
7 回答5.3k 阅读
6 回答6.8k 阅读✓ 已解决
4 回答2.3k 阅读
1 回答3.3k 阅读
2 回答909 阅读✓ 已解决
2 回答2.2k 阅读
1 回答2.2k 阅读
不,谷歌的权力选择不支持这一点。
https://groups.google.com/forum/#!topic/golang-nuts/-5MCaivW0qQ