在Go语言中,当方法由*Type调用时,你如何创建一个接口?

huangapple go评论87阅读模式
英文:

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 不符合。你可以选择:

  1. 修改你的代码,使方法直接操作非指针类型 Char(这样也会自动适用于 *Char
  2. 只在需要与类型 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

  1. change your code so that the methods operate on the non-pointer type Char directly (which will automatically also work for *Char too)
  2. only use *Char when you need something to be compatible with type DB

huangapple
  • 本文由 发表于 2011年6月22日 14:04:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/6435587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定