douluan1533 2019-07-19 10:01
浏览 182
已采纳

无法在非本地类型模型上定义新方法。

I want to put all my models in a shared Common lib.

So, I made a new repo: gitlab.com/xxx/common

Inside I put a package: models

Here is the definition of an object:

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

Now, I want to use it in an external project, I do:

go get gitlab.com/xxx/common

And Go Modules will download it.

I import use it like that:

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
}

But Goland will not resolve it, and when I compile, I get:

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

Why is it happening and what can I do to fix it ?

  • 写回答

1条回答 默认 最新

  • dqcuq4138 2019-07-19 10:22
    关注

    It is not allowed to define methods outside the package where the type is defined. This leaves you with a couple of options:

    1. Define the methods in the models package. That's the simplest approach when dealing with your own code but of course won't work for 3rd-party types.

    2. Create a regular function instead of a method (func String(meter models.Meter) string). That might be less idiomatic, though (especially for the String method), and also does not have access to private fields (unless you define the function in the models package, in which case you could just define the method instead).

    3. Create a new type embedding the original type. That would be a bit cumbersome to use but allows you to extend existing behavior. Something like this:

    `

    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"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探