登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-02-26 12:21:25 151浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《无法在指定类型的类型定义上调用方法》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我正在使用 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

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

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 是新类型,它们没有基础类型的方法。您应该直接使用记录器类型而不创建新类型,或者使用嵌入定义新的记录器类型。当您定义新的结构类型并嵌入记录器时,新类型将具有嵌入类型的方法。当您像您一样定义新类型时,新类型将不具有其基类型的方法。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>