关闭
douteng5673 2014-11-17 04:20
浏览 79
已采纳

在golang中使用空白标识符导入的用例

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?

  • 写回答

3条回答 默认 最新

  • dst2007 2014-11-17 04:37
    关注

    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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部