英文:
In golang, how do you access a method that takes a pointer receiver and is also in a different package?
问题
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{1, "a", "b", "c", "d", true, true}
err := model.Update(&cur, "a", "b", "c", "d", true, true)
}
在上面的代码块中,我试图调用一个接收器指针的方法,该方法位于“model”包中。
这个代码的编译错误是:
对未定义的字段或方法'model'的引用
err := cur.model.Update(a,b,c,d,e,true,true)
在下面的代码块中,包“model”中的方法“Update”接收一个指向结构体的接收器指针和其他输入参数。
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”,同时输入一个接收器指针?
英文:
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)
}
In the code block above, I am trying to call a method that takes a receiver pointer and that is located in package "model".
The compiler error for this is:
reference to undefined field or method ‘model’
err := cur.model.Update(a,b,c,d,e,true,true)
In the code block below,the method "Udpate" in package "model" takes a receiver point to a struct and other input parameters.
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 */
}
I know for functions in other packages I can call them in my current package by saying:
packageName.method(parameters)
How could I call method "Update" from package "model" in package "tests" while inputting a receiver pointer when I call it?
答案1
得分: 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)
英文:
func (update *Struct) Update(a, b, c, d, e string, f, g bool)
is a method that is defined on type model.Struct
. You cannot call it on a different type, such as TestStruct
defined in your tests package.
What you probably want to do is:
cur := model.Struct{i,a,b,c,d,true,true}
err := cur.Update(a,b,c,d,true,true)
答案2
得分: 2
例如,
package tests
import (
"dir/model"
"testing"
)
func TestUpdate(t *testing.T) {
t.Log("更新中")
cur := model.Struct{i, a, b, c, d, true, true}
err := cur.Update(a, b, c, d, true, true)
}
英文:
For example,
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论