用于在golang中使用空白标识符导入的用例 [英] A use case for importing with blank identifier in golang
问题描述
例如:
import _foo / bar
我很难想象这个构造的用例。 使用`import`语句提供了一种用法数据库驱动程序可以在不需要导入程序的情况下使用该程序包的任何导出函数的情况下加载,但是它将细节留给了读者的想象。
有没有真实的例子(用代码片段和解释)来说明这个用例? 我正在写一个图片缩放器。我希望它能够读取不同格式的图像,如 JPEG , PNG & 并将它们输出到 JPEG 中。 所以除了 image
和 image / jpeg
包,我还必须导入 image / png
和 image / gif
仅用于注册各自的解码器。
<如果我没有导入这些图片,缩放图片只能读取JPEG图片。
package main
导入(
image
image / jpeg//我想将图像导出为JPEG
_ image / png
_image / gif
)
// ...
图片 code>
包:
解码任何特定的图像格式需要预先注册解码器功能。注册通常是自动的,因为初始化该格式的包的副作用,以便解码PNG图像,只需要:
import _image / png
The Go programming language specification states: "To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name."
For example:
import _ "foo/bar"
I am having difficulty imagining a use case for this construct. The accepted answer for Usage of the `import` statement mentions a use case where a database driver may be loaded without the need for the importing program to use any of the exported functions of that package, but it leaves out the details to reader's imagination.
Are there real life examples (with code snippets and explanation) that illustrate this use case?
I was writing an image scaler. I wanted it to be able to read images in different formats like JPEG, PNG & GIF and output them in JPEG.
So in addition to the image
and image/jpeg
packages, I also had to import image/png
and image/gif
only to register their respective decoders.
Had I not imported those, the scaler would only be able to read JPEG images.
package main
import(
"image"
"image/jpeg" // I wanted to export the images as JPEG
_ "image/png"
_ "image/gif"
)
// ...
The relevant documentation from the image
package:
Decoding any particular image format requires the prior registration of a decoder function. Registration is typically automatic as a side effect of initializing that format's package so that, to decode a PNG image, it suffices to have:
import _ "image/png"
这篇关于用于在golang中使用空白标识符导入的用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!