有没有一种方法可以在Go函数中指定默认值?我正在尝试在文档中找到它,但是找不到任何指定这是可能的东西。
func SaySomething(i string = "Hello")(string){
...
}
Answers:
不,Google的权力选择不支持这一点。
https://groups.google.com/forum/#!topic/golang-nuts/-5MCaivW0qQ
否,但是还有其他一些选项可以实现默认值。关于这个主题有一些不错的博客文章,但是这里有一些具体的例子。
// 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 {
就像大多数其他现代语言一样,它将任何给定的示例都简化为一行代码。
不,没有办法指定默认值。我相信这样做的目的是为了提高可读性,但要花更多时间(并且希望是在作者端)花些时间。
我认为拥有“默认”的正确方法是拥有一个新功能,该功能将默认提供给更通用的功能。有了这个,您的代码就变得更加清晰了。例如:
func SaySomething(say string) {
// All the complicated bits involved in saying something
}
func SayHello() {
SaySomething("Hello")
}
花费很少的精力,我做了一个做普通事情的函数并重用了通用函数。您可以在许多库中看到这一点,fmt.Println
例如,仅在其他情况下添加换行符即可fmt.Print
。但是,在阅读某人的代码时,很明显他们通过调用的函数打算做什么。使用默认值时,如果不使用函数来引用默认值的实际含义,我将不知道会发生什么。