duanjue6584 2019-01-08 19:43 采纳率: 100%
浏览 56
已采纳

调用提升函数时发生未定义的错误

I am getting an undefined error when using a promoted function in GO.

import "log"
type logger struct {
    log.Logger
}

logError := logger.New(os.Stderr, "ERROR", log.LstdFlags)
logOut := logger.New(os.Stdout, "INFO", log.LstdFlags)

This results in compiler error:

logger.go: logger.New undefined (type logger has no method New)

However, New is a promoted function of the log.Logger. What is wrong here?

  • 写回答

1条回答 默认 最新

  • dongquexi1990 2019-01-08 19:45
    关注

    There is no Logger.New() method, only a log.New() function that returns a value of *log.Logger:

    func New(out io.Writer, prefix string, flag int) *Logger
    

    Generated go doc deliberately lists such "constructor" functions under the type they return so you can easily find them, but this grouping doesn't make them methods. log.New() has no receiver so it cannot be a method, only a function.

    You may use log.New() to obtain a value of type *log.Logger, which if you dereference, you get a value of type log.Logger, the value you embed.

    However, if something is handed to you as a pointer in the first place, that is a strong indication that you should work with it as a pointer (and shouldn't dereference it). So I'd embed *log.Logger, methods will still get promoted (because they have pointer receiver). This is how you could initialize your loggers:

    type logger struct {
        *log.Logger
    }
    
    var logError = logger{
        Logger: log.New(os.Stderr, "ERROR", log.LstdFlags),
    }
    
    var logOut = logger{
        Logger: log.New(os.Stdout, "INFO", log.LstdFlags),
    }
    

    Although if you add nothing else to your logger type, I don't see its existence justified, you could use *log.Logger as well.

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵