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

Can't call methods on a type definition of a given type

我正在使用 Google Wire 进行依赖注入,我想要 2 个记录器(错误和信息)。所以我创建了以下提供程序:

type errorLogger *log.Logger
type infoLogger  *log.Logger

type 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 方法(例如 PrintlnFatalf 等)

我想我引用的东西不正确,只是不确定是什么。

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

查看 Go 规范,类型声明 > Type Definitions:

A defined type may have methods associated with it. It does not inherit any methods bound to the given type, but the method set of an interface type or of elements of a composite type remains unchanged

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方法不在errorLoggerinfoLoggermethod set中。

您可以使用组合:

type errorLogger struct {
   *log.Logger
}

然后你可以初始化它:

&Logger{
    Error: errorLogger{
        Logger: log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile),
    },
}

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