为了账号安全,请及时绑定邮箱和手机立即绑定

无法在给定类型的类型定义上调用方法

无法在给定类型的类型定义上调用方法

Go
幕布斯7119047 2022-06-13 17:19:40
我正在使用 Google Wire 进行依赖注入,我想要 2 个记录器(错误和信息)。所以我创建了以下提供程序:type errorLogger *log.Loggertype infoLogger  *log.Loggertype Logger struct {  Error errorLogger  Info  infoLogger}func ProvideLogger() *Logger {  return &Logger{    Error: log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile),    Info:  log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime),  }}在我的代码中,我这样引用记录器h.Logger.Error但是,这并没有让我像我想象的那样访问这些logger方法(例如Println,Fatalf等)我假设我引用的东西不正确,只是不确定是什么。
查看完整描述

2 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

定义为的新类型type errorLogger *log.Logger不继承基础类型的方法。


请参阅 Go 规范、类型声明 >类型定义:


定义的类型可能具有与之关联的方法。它不继承绑定到给定类型的任何方法,但接口类型或复合类型元素的方法集保持不变


type Mutex struct         { /* Mutex fields */ }

func (m *Mutex) Lock()    { /* Lock implementation */ }

func (m *Mutex) Unlock()  { /* Unlock implementation */ }


// NewMutex has the same composition as Mutex but its method set is empty.

type NewMutex Mutex


// The method set of PtrMutex's underlying type *Mutex remains unchanged,

// but the method set of PtrMutex is empty.

type PtrMutex *Mutex

由此可见Printf和 其他*log.Logger方法不在 和的方法集中。errorLoggerinfoLogger


您可以使用组合:


type errorLogger struct {

   *log.Logger

}

然后你可以初始化它:


&Logger{

    Error: errorLogger{

        Logger: log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile),

    },

}


查看完整回答
反对 回复 2022-06-13
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

两个新的 logger 类型 errorLogger 和 infoLogger 是新类型,它们没有底层类型的方法。您应该直接使用记录器类型而不创建新类型,或者使用嵌入定义新的记录器类型。当您定义新的结构类型并嵌入记录器时,新类型将具有嵌入类型的方法。当您像您一样定义新类型时,新类型将没有其基本类型的方法。



查看完整回答
反对 回复 2022-06-13
  • 2 回答
  • 0 关注
  • 88 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信