dsadsa123111 2015-04-18 04:31
浏览 45

在golang中,如何覆盖嵌入式结构的方法

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
", b)
    fmt.Printf("%+v
", 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
", b)
    fmt.Printf("%+v
", s)
}
  • 写回答

2条回答 默认 最新

  • doutangshuan6473 2015-04-18 04:43
    关注

    I think I should use the interface here, it achieve what I want, but affected the base

    func main() {
        t16()
    }
    
    type Base interface {
        Set(int)
    }
    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.Set(1)
        var b Base = s
        fmt.Printf("%+v
    ", b)
        fmt.Printf("%+v
    ", s)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统