douzhenyu6533 2019-03-03 05:53
浏览 1427
已采纳

解决Go中循环依赖的最佳实践

I have a Go project that contains both of these packages:

  • logging
    Imports config, because I want to send the current configuration to my error reporting system
  • config
    Imports logging, because I want to log if the program is unable to open the config files

What is the best practice for resolving this dependency error?

  • 写回答

1条回答 默认 最新

  • duangelin7513 2019-03-03 06:24
    关注

    In what format are you sending the configuration to the error reporting system? Maybe pass that to logging? Say, if it's json, then marshal the config before giving it to logging and then give logging the []byte result only.

    But in general, if two packages depend on each other directly what you can do is have one of them declare an interface that matches the other one's behaviour and then have a separate package pass the concrete instance as the interface.

    For example:

    /myapp/config

    import "myapp/logging"
    
    type Config struct {
         // ...
    }
    
    func NewConfig() *Config {
        // ...
        if err != nil {
            logging.LogError(err)
        }
    }
    

    /myapp/logging

    import "myapp/config"
    
    func LogConfig(c *config.Config) {
        // ...
    }
    
    func LogError(err error) {
        // ...
    }
    

    So in this case you could declare an interface in the config package that matches the behaviour it needs from logging.

    /myapp/config

    type Logging interface {
        LogError(error)
    }
    
    var logging Logging
    
    func SetLogging(l Logging) {
        logging = l
    }
    
    type Config struct {
         // ...
    }
    
    func NewConfig() *Config {
        // ...
        if err != nil {
            logging.LogError(err)
        }
    }
    

    And then have a type in the logging package implement that interface by simply delegating to the original functions.

    /myapp/logging

    import "myapp/config"
    
    func LogConfig(c *config.Config) {
        // ...
    }
    
    func LogError(err error) {
        // ...
    }
    
    type Logging struct{}
    
    func (Logging) LogError(err error) {
        LogError(err)
    }
    

    And lastly have a third package make it all work together.

    /myapp

    import "myapp/config"
    import "myapp/logging"
    
    func init() {
        config.SetLogging(logging.Logging{})
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程