【发布时间】:2013-11-05 21:44:58
【问题描述】:
有没有办法在 Go 的函数中指定默认值?我试图在文档中找到它,但我找不到任何说明这是可能的。
func SaySomething(i string = "Hello")(string){
...
}
【问题讨论】:
标签: go default-value function-call default-arguments
有没有办法在 Go 的函数中指定默认值?我试图在文档中找到它,但我找不到任何说明这是可能的。
func SaySomething(i string = "Hello")(string){
...
}
【问题讨论】:
标签: go default-value function-call default-arguments
否,但还有一些其他选项可以实现默认值。关于这个主题有一些good blog posts,但这里有一些具体的例子。
// 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)
}
// 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)
}
// 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)
}
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)
}
【讨论】:
func Concat1(a string = 'foo', b int = 10) string {,就像在大多数其他现代语言中一样...它将任何给定的示例几乎都减少到一行代码。
不,Google 的权力选择不支持这一点。
https://groups.google.com/forum/#!topic/golang-nuts/-5MCaivW0qQ
不,无法指定默认值。我相信这样做是为了提高可读性,但代价是作者付出了更多的时间(希望是思考)。
我认为拥有“默认值”的正确方法是拥有一个新函数,该函数将默认值提供给更通用的函数。有了这个,你的代码就更清楚你的意图了。例如:
func SaySomething(say string) {
// All the complicated bits involved in saying something
}
func SayHello() {
SaySomething("Hello")
}
不费吹灰之力,我制作了一个做普通事情的函数,并重用了通用函数。您可以在许多库中看到这一点,例如 fmt.Println 只需在 fmt.Print 否则会执行的操作中添加一个换行符。然而,在阅读某人的代码时,他们调用的函数很清楚他们打算做什么。使用默认值,如果不去函数引用默认值实际是什么,我将不知道应该发生什么。
【讨论】: