【问题标题】:cannot define new methods on non-local type models.Meter无法在非本地类型模型上定义新方法。仪表
【发布时间】:2021-01-05 23:39:29
【问题描述】:

我想把我所有的模型放在一个共享的 Common 库中。

所以,我做了一个新的回购:gitlab.com/xxx/common

我在里面放了一个包:models

这是一个对象的定义:

type Meter struct {
    ID           string
    OperationID  string
    Type         ConsoProd
    Unit         string
    Timestep     time.Duration
    Measures     []Measure 
    FetchMethod  AcquisitionMethod
    Metadata     interface{}
}

现在,我想在外部项目中使用它:

go get gitlab.com/xxx/common

Go Modules 会下载它。

我这样导入使用它:

import "gitlab.com/xxx/common/models"

//String transparent method
func (meter models.Meter) String() string {
    var stringifyMeter string
    stringifyMeter += "Meter " + meter.ID + " is a " + meter.Type.String() + " and compute in operation #" + meter.OperationID + "."
    return stringifyMeter
}

但是Goland不会解决它,当我编译时,我得到:

cannot define new methods on non-local type models.Meter

为什么会发生,我可以做些什么来解决它?

【问题讨论】:

    标签: go go-modules


    【解决方案1】:

    不允许在定义类型的包之外定义方法。这为您提供了两种选择:

    1. models 包中定义方法。这是处理您自己的代码时最简单的方法,但当然不适用于 3rd-party 类型。

    2. 创建常规函数而不是方法 (func String(meter models.Meter) string)。不过,这可能不那么惯用(特别是对于String 方法),并且也无法访问私有字段(除非您在models 包中定义了该函数,在这种情况下您可以只定义该方法) .

    3. 创建嵌入原始类型的新类型。这使用起来有点麻烦,但允许您扩展现有行为。像这样:

    `

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        myTime := MyTime{time.Now()}
        fmt.Println(myTime)        /* behaves as time.Time */ 
        fmt.Println(myTime.Foo())  /* also has extra methods */
    }
    
    type MyTime struct {
      time.Time
    }
    
    func (m MyTime) Foo() string {
      return "foo"
    }
    

    【讨论】:

    • 好的!选项一有意义!感谢您的帮助
    【解决方案2】:

    简单,

    import ...bla/bla/Meter
    
    type extended Meter
    

    参考:https://github.com/golang/go/issues/31631#issuecomment-486075295

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      相关资源
      最近更新 更多