【问题标题】:In golang, how do you access a method that takes a pointer receiver and is also in a different package?在 golang 中,你如何访问一个接受指针接收器并且也在不同包中的方法?
【发布时间】:2016-06-29 00:24:23
【问题描述】:
package tests

import (
    "testing"
    "strconv"
    "dir/model"
)

type TestStruct struct {
    ID int
    a  string
    b  string
    c  string
    d  string
    ac bool
    ad bool
}

func TestUpdate(t *testing.T) {

        t.Log("Updating")
        cur := TestStruct{i,a,b,c,d,true,true}
        err := cur.model.Update(a,b,c,d,true,true)
}

在上面的代码块中,我试图调用一个方法,该方法采用接收器指针并且位于包“模型”中。

编译器错误是:

对未定义字段或方法“模型”的引用 err := cur.model.Update(a,b,c,d,e,true,true)

在下面的代码块中,包“model”中的方法“Udpate”将接收器指向结构和其他输入参数。

package model

type Struct struct {
    ID int
    a  string
    b  string
    c  string
    d  string
    ac bool
    ad bool
}

func (update *Struct) Update(a, b, c, d,
e string, f, g bool) error {

    /* code */

}

我知道其他包中的函数,我可以在当前包中通过以下方式调用它们:

packageName.method(parameters) 

当我调用它时输入接收器指针时,如何从包“tests”中的包“model”调用方法“Update”?

【问题讨论】:

  • 样式指针。在 Go 中,建议将包“p”的测试放在包“p”中,这是测试非导出函数的唯一方法。

标签: methods go packages receiver


【解决方案1】:

例如,

package tests

import (
    "dir/model"
    "testing"
)

func TestUpdate(t *testing.T) {
    t.Log("Updating")
    cur := model.Struct{i, a, b, c, d, true, true}
    err := cur.Update(a, b, c, d, true, true)
}

【讨论】:

    【解决方案2】:
    func (update *Struct) Update(a, b, c, d, e string, f, g bool)
    

    是在类型model.Struct 上定义的方法。您不能在其他类型上调用它,例如在您的测试包中定义的TestStruct

    你可能想做的是:

        cur := model.Struct{i,a,b,c,d,true,true}
        err := cur.Update(a,b,c,d,true,true)
    

    【讨论】:

      猜你喜欢
      • 2014-07-30
      • 2018-02-28
      • 2016-02-29
      • 1970-01-01
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      相关资源
      最近更新 更多