`init()` vs declaration in Go

huangapple go评论73阅读模式
英文:

`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.

huangapple
  • 本文由 发表于 2022年5月26日 04:26:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/72383788.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定