douqiao8370 2015-09-01 14:16
浏览 34

Go中的原型结构

My use case is, I need to have several structs in Go, who will have methods of same signatures and not necessarily have to have all the methods. The following code describes the requirements and also represents my current solution.

type calc struct {
    fn func(a, b int) int
    gn func(a string) bool
    name string
}

func add(a, b int) int {
    return a + b
}

func bar(foo string) bool {
    // do something
}

func sub(a, b int) int {
    return a - b
}

func main() {
    for c := range []calc{{
        fn: add,
        gn: bar,
        name: "addition",
    }, {
        fn: sub,
        name: "subtraction",
    }} {
        fmt.Printf("%s(10, 15) returned: %d
", c.name, c.fn(10, 15))
        if c.gn != nil {
            c.gn(c.name)
        }
    }
}

My question is how to improve this code? What's the best way to achieve this in Go? Can I achieve a better solution using interface?

  • 写回答

2条回答 默认 最新

  • dst3605528 2015-09-01 14:25
    关注

    Use interfaces.

    type Op interface {
        Name() string
        Do(a, b int) int
    }
    
    type Add struct{}
    
    func (Add) Name() string    { return "add" }
    func (Add) Do(a, b int) int { return a + b }
    
    type Sub struct{}
    
    func (Sub) Name() string    { return "sub" }
    func (Sub) Do(a, b int) int { return a - b }
    

    Playground: http://play.golang.org/p/LjJt6D0hNF.


    EDIT: Since you've edited your question, here is an example of how you could use asserting and interface to a broader interface for your task:

    type RevOp interface {
        Op
        ReverseDo(a, b int) int
    }
    
    // ...
    
    func (Add) ReverseDo(a, b int) int { return a - b }
    
    // ...
    
    fmt.Printf("%s(10, 15) returned: %d
    ", op.Name(), op.Do(10, 15))
    if op, ok := op.(RevOp); ok {
        fmt.Printf("reverse of %s(10, 15) returned: %d
    ", op.Name(), op.ReverseDo(10, 15))
    }
    

    Playground: http://play.golang.org/p/MQ6LlPDcEi.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器