英文:
In go, how do you create an interface when methods are called by *Type?
问题
type Char string
func (*Char) toType(v *string) interface{} {
if v == nil {
return (*Char)(nil)
}
var s string = *v
ch := Char(s[0])
return &ch
}
func (v *Char) toRaw() *string {
if v == nil {
return (*string)(nil)
}
s := *((*string)(v))
return &s
}
type DB interface{
toRaw() *string
toType(*string) interface{}
}
Char does not implement DB (toRaw method requires pointer receiver)
Is there a way to create an interface from toType
and toRaw
, or do I need to backup and have the receivers be the types themselves and not pointers to types?
英文:
Attempting to create an interface, but methods have *Type
, not Type
receivers
APOLOGIZE: was sleepy and mis-read error messages. Thought I was being block from creating the DB interface when in reality I was mis-using it. Sorry about that... will be more careful in the future!
<pre>
type Char string
func (*Char) toType(v *string) interface{} {
if v == nil {
return (*Char)(nil)
}
var s string = *v
ch := Char(s[0])
return &ch
}
func (v *Char) toRaw() *string {
if v == nil {
return (*string)(nil)
}
s := *((*string)(v))
return &s
}
</pre>
from here I would like an interface that contains the methods toType
and toRaw
<pre>
type DB interface{
toRaw() *string
toType(*string) interface{}
}
</pre>
does not work since the function receivers are pointers. I say this because when I try to use it I get the error.k
<pre>
Char does not implement DB (toRaw method requires pointer receiver)
</pre>
Is there a way to create an interface from toType
and toRaw
, or do I need to backup and have the receivers be the types themselves and not pointers to types?
答案1
得分: 5
如果你为指针类型定义了接口方法,那么在调用期望接口的方法/函数时,你必须传递一个指针。
英文:
If you define your interface methods for the pointer type you must pass a pointer to the methods/functions expecting the interface.
答案2
得分: 3
我不明白你的问题是什么。是的,按照你的写法,*Char
符合接口 DB
,而 Char
不符合。你可以选择:
- 修改你的代码,使方法直接操作非指针类型
Char
(这样也会自动适用于*Char
) - 只在需要与类型
DB
兼容时使用*Char
。
英文:
I don't understand what your problem is. Yes, the way you've written it, *Char
conforms to the interface DB
and Char
doesn't. You can either
- change your code so that the methods operate on the non-pointer type
Char
directly (which will automatically also work for*Char
too) - only use
*Char
when you need something to be compatible with typeDB
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论