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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c