在Golang中,如何覆盖嵌入式结构的方法
代码在这里
package main
import "fmt"
func main() {
t16()
}
type Base struct {
val int
}
func (b *Base)Set(i int) {
b.val = i
}
type Sub struct {
Base
changed bool
}
func (b *Sub)Set(i int) {
b.val = i
b.changed = true
}
func t16() {
s := &Sub{}
s.Base.Set(1)
var b *Base = &s.Base
fmt.Printf("%+v\n", b)
fmt.Printf("%+v\n", s)
}
我想将Sub Act作为基础,但是当我调用SET设置时我知道Golang没有多态性或代理,但是有什么方法可以做到这一点,并且不影响基础?
更新了
我希望当我致电base时。设置将标记更改,对于用户,他们不知道自己实际使用该子,因此我可以监视基本的行为。
func t16() {
s := &Sub{}
var b *Base = &s.Base
b.Set(10)
fmt.Printf("%+v\n", b)
fmt.Printf("%+v\n", s)
}
Code here
package main
import "fmt"
func main() {
t16()
}
type Base struct {
val int
}
func (b *Base)Set(i int) {
b.val = i
}
type Sub struct {
Base
changed bool
}
func (b *Sub)Set(i int) {
b.val = i
b.changed = true
}
func t16() {
s := &Sub{}
s.Base.Set(1)
var b *Base = &s.Base
fmt.Printf("%+v\n", b)
fmt.Printf("%+v\n", s)
}
I want to make Sub act as Base, but when I call Set, for Sub it will mark the changed.I know there is no polymorphism or proxy in golang, but is there any way to do this, and not effect the Base?
UPDATED
I hope when I call Base.Set it will mark the change, for user, they don't know they actually use the Sub, so I can monitor the Base behave.
func t16() {
s := &Sub{}
var b *Base = &s.Base
b.Set(10)
fmt.Printf("%+v\n", b)
fmt.Printf("%+v\n", s)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过拥有
sub
嵌入base
它自动具有Base
的字段和功能,作为sub sub 。这意味着您可以直接调用
s.val
,并且您 可以调用s.set
调用基本函数除外因为sub
实现了自己的set
方法, hides 。当您调用
s.base.set.set()
中时,您绕过sub.seb.set.set()
,直接调用base.set.set.set()
。在您的情况下修复它就像调用
s.set()
而不是s.base.set.set()
一样简单。这对我有用:
” >也可以调用嵌入式结构方法,感觉很像
super()
键入其他OO语言提供的继承。By having
Sub
embedBase
it automatically has all ofBase
's fields and functions made available as top level members ofSub
. This means you can directly calls.val
, and you would be able to calls.Set
to invoke the base function except for the fact thatSub
implemented its ownSet
method which hides the Base one.When you call
s.Base.Set()
in your example you are bypassingSub.Set()
and directly callingBase.Set()
.To fix it in your case is as simple as calling
s.Set()
instead ofs.Base.Set()
.This works for me:
Play link
Notice that
Sub.Set()
can invoke the embedded structs method as well, which feels a lot like thesuper()
type inheritance that other oo languages provide.