doutao6653 2015-09-08 19:09
浏览 130
已采纳

golang什么是导入副作用

import (
    _ "github.com/lib/pq"
    _ "image/png"
    ...
)

In effective go it says that these kinds of imports mean side effect. I've read several SO answers but none explain what is an import side effect. Could someone elaborate the term import side effect?

  • 写回答

1条回答 默认 最新

  • dowm41315 2015-09-08 19:14
    关注

    When they say 'import side effects' they are essentially referring to code/features that are used statically. Meaning just the import of the package will cause some code to execute on app start putting my system in a state different than it would be without having imported that package (like code in an init() which in their example registers handlers, it could also lay down config files, modify resource on disc, ect). The effective go tutorial is explaining this simply to illustrate reasons why a developer might want to do a blank import ie; import _ "somepackageImNotUsingReally"

    EDIT: to add additional context when I said init() I was referring to this method; https://golang.org/doc/effective_go.html#init - any imported packages will have their init methods called prior to main being called. Whatever is in the init() is a side effect. I don't think there can be any others because things like constants will be at the package scope, not the global scope so it wouldn't redefine constants or anything like that.

    EDIT2: as pointed out in comments and explained in the init link above " is called after all the variable declarations in the package have evaluated their initializers" meaning code like PackageScopeVar := unexportedInitializerThatWritesToDisc() will run and could have side effects.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP