douteng5673 2014-11-17 12: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 12: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条)

报告相同问题?

悬赏问题

  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?