英文:
Interface that returns it's self (Cloneable)
问题
我正在尝试创建一个可克隆接口,并且在让结构体实现该接口时遇到了一些问题。这似乎是Go语言的一个限制,在许多其他语言中并不存在。我正在试图理解这个限制的理由。
var _ Cloneable = test{}
type Cloneable interface {
Clone() Cloneable
}
type test struct {
}
func (t *test) Clone() *test {
c := *t
return &c
}
补充问题,因为这对我来说仍然很奇怪。这段代码也无法编译通过。
var _ Cloneable = &test{}
type Cloneable interface {
Clone() Cloneable
}
type Cloneable2 interface {
Clone() Cloneable2
}
type test struct {
}
func (t *test) Clone() Cloneable2 {
c := *t
return &c
}
英文:
I'm trying to create a cloneable interface and am running into some problems getting structs to implement the interface. It appears this is a limit of go which isn't in many other langauges. I'm trying to understand the justification for this limit.
var _ Cloneable = test{}
type Cloneable interface {
Clone() Cloneable
}
type test struct {
}
func (t *test) Clone() *test {
c := *t
return &c
}
Playground: https://play.golang.org/p/Kugatx3Zpw
Followup question since it still seems weird to me. This also does not compile
var _ Cloneable = &test{}
type Cloneable interface {
Clone() Cloneable
}
type Cloneable2 interface {
Clone() Cloneable2
}
type test struct {
}
func (t *test) Clone() Cloneable2 {
c := *t
return &c
}
Playground: https://play.golang.org/p/jlyMDPF1WB
答案1
得分: 4
为了满足接口方法的要求,参数和返回类型必须使用接口声明中使用的相同类型。Clone
方法必须返回一个Cloneable
类型以满足接口要求:
func (t *test) Clone() Cloneable {
c := *t
return &c
}
Clone
方法不能返回*test
或Cloneable2
类型,因为这些类型不是Cloneable
类型。
指针类型实现了接口:
var _ Cloneable = &test{}
由于test
类型必须满足Cloneable
接口才能编译Clone
方法,因此不需要进行编译时断言。
(问题是一个移动目标。这是对问题的两次先前编辑的回答。)
英文:
To satisfy an interface method, the argument and return types must use the same types used in the interface declaration. The Clone
method must return a Cloneable
to satisfy the interface:
func (t *test) Clone() Cloneable {
c := *t
return &c
}
The Clone
method cannot return a *test
or Cloneable2
because these types are not the Cloneabl
e type.
The pointer type implements the interface:
var _ Cloneable = &test{}
Because the test
type must satisfy the Cloneable
interface for the Clone
method to compile, this compile time assertion is not needed.
(The question is a moving target. This is an answer to two previous edits of the question.)
答案2
得分: 0
我找到了这个讨论帖子,其中提到支持协变函数类型会使语言变得更难理解,而收益却很小。至少他们做出了一个有意识的决定,不支持大多数其他语言支持的功能。我不太认同,但无论如何...
英文:
I found this thread which talks about it and the answer seems to be supporting covariant function types would make the language harder to understand for little benefit. https://github.com/golang/go/issues/7512
At least they made a conscious decision to not support a feature supported by most other languages. I don't really buy it, but oh well...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论