假设我厌倦了在所有地方键入 System.out.println(message)
,我在 java 中引入了一个方法,看起来像
private void print (Object message) {
System.out.println(message);
}
我会在必要时在 java 中调用 print (2)
& print ("hi")
。
在 Go 语言中也能实现同样的目标吗?类似这样的函数
func print(message ) {
fmt.Println (message)
}
最佳答案
Go 是一个 procedural programming语言有很多functional programming元素。
函数是Go中的一等类型,你可以创建函数类型的变量,你可以将函数值赋给这些变量,你可以调用它们(其中存储的函数值)。
所以你可以简单地做:
var myprint = fmt.Println
myprint("Hello, playground")
myprint(1, 3.14, "\n", time.Now())
上面的输出(在 Go Playground 上尝试):
Hello, playground
1 3.14
2009-11-10 23:00:00 +0000 UTC m=+0.000000001
上述myprint
变量的优点是它将具有与fmt.Println()
相同的签名。 ,即:
func Println(a ...interface{}) (n int, err error)
是的,我们还可以创建一个包装函数,例如:
func myprint(a ...interface{}) (n int, err error) {
return fmt.Println(a...)
}
它的工作方式与调用 fmt.Println()
相同,但使用变量不那么冗长,而且它的优点是您可以在运行时更改函数值,这在编写测试时非常方便(有关示例,请参阅 Testing os.Exit scenarios in Go with coverage information (coveralls.io/Goveralls) )。
关于该主题的更多信息:
Dave Cheney: Do not fear first class functions
golangbot.com: First Class Functions
还有一种可能性是使用“点导入”,但我建议不要这样做:
import (
. "fmt"
)
func main() {
Println("Hello, playground")
}
当您使用“点导入”时,无需使用 qualified identifiers 即可访问导入包的所有导出标识符。 .引自 Spec: Import declarations:
If an explicit period (
.
) appears instead of a name, all the package's exported identifiers declared in that package's package block will be declared in the importing source file's file block and must be accessed without a qualifier.
关于go - 相当于Java在GoLang中将Object作为方法参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52851540/