英文:
`init()` vs declaration in Go
问题
我正在翻译以下内容:
我有点难以理解为什么在Go语言中使用init()
函数是有用的。一般来说,你在init()
函数中做的任何事情都可以通过在Go文件中进行声明来完成。
具体来说,这两个文件之间有什么实际的区别呢?
// useInit.go
package main
var answer int
func init() {
answer = 42
}
// useDeclaration.go
package main
var answer int = 42
请注意,我只翻译了代码部分,其他内容不包括在内。
英文:
I'm having a little trouble understanding why init()
is useful in Go. It seem that generally, anything you do in init()
could be done via a declaration in the go file instead.
To put a fine point on, what's the practical difference between these two files?
// useInit.go
package main
var answer int
func init() {
answer = 42
}
// useDeclaration.go
package main
var answer int = 42
答案1
得分: 2
如果你为其他应用程序制作一个包,并且没有主函数,但是在应用程序运行之前必须执行某些操作(并确保完成),你可以在init()
函数中完成。而且为了运行这个函数,宿主应用程序不需要做任何事情,甚至不需要使用你的包中的任何函数。一个很好的例子是mysql驱动(github.com/go-sql-driver/mysql
)。它的init()
函数如下所示:
func init() {
sql.Register("mysql", &MySQLDriver{})
}
当你使用以下方式导入它时:
import _ "github.com/go-sql-driver/mysql"
mysql驱动将被注册,因此SQL包可以连接到MySQL服务器,但是你没有做任何事情,甚至没有使用这个包中的任何函数。
在这种情况下,导入的名称应该是一个下划线,告诉编译器不要移除该包,然而看起来你并没有用它做任何事情。
英文:
If you make a package for used in other applications and don't have a main, but you have to do something (and be sure to be done) before the app is running, you can do it in the init()
. And for this to run, the host app doesn't need to do anything, it doesn't even have to use any func from your package. Good example is the mysql driver (github.com/go-sql-driver/mysql
). It's init() func looks like this:
func init() {
sql.Register("mysql", &MySQLDriver{})
}
And when you import it using
import _ "github.com/go-sql-driver/mysql"
The mysql driver will be registered, so the SQL package can connect to a MySQL server, however you didn't do anything, don't even use a func from this package.
In this case the import name should be an underscore to tell the compiler to not remove the package, however it looks like you don't use it for anything.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论