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条)

报告相同问题?

悬赏问题

  • ¥60 求直线方程 使平面上n个点在直线同侧并且距离总和最小
  • ¥50 java算法,给定试题的难度数量(简单,普通,困难),和试题类型数量(单选,多选,判断),以及题库中各种类型的题有多少道,求能否随机抽题。
  • ¥50 rk3588板端推理
  • ¥250 opencv怎么去掉 数字0中间的斜杠。
  • ¥15 这种情况的伯德图和奈奎斯特曲线怎么分析?
  • ¥250 paddleocr带斜线的0很容易识别成9
  • ¥15 电子档案元素采集(tiff及PDF扫描图片)
  • ¥15 flink-sql-connector-rabbitmq使用
  • ¥15 zynq7015,PCIE读写延时偏大
  • ¥15 使用spss做psm(倾向性评分匹配)遇到问题