dtv8189 2018-12-01 07:32
浏览 68
已采纳

函数接受抽象接口和函数接受struct实现之间的golang转换

An issue I met when creating a layer on top of different version of implementations. The goal is to abstract out the implementation details and the caller doesn't need to care which implementation we are using.

Please see the code example here

^ The code can better explain the issue I met.

We have two version of Stream implementation Stream1 and Stream2. They have a common interface Stream.

Both of them have a corresponding BindStreamHandler function accepting StreamHandler1 or StreamHandler2.

We have a function BindStreamHandler, and a general implementation of func StreamHandlerImpl(s Stream). No matter we use Stream1 or Stream2, the general implementation is the same.

Now I face an issue downcasting StreamHandlerImpl (accepting abstract Stream to StreamHandler1 (accepting Stream1).


Update:

I found this version worked.

func BindHandler(h interface{}) {
    if Version == 1 {
        h1 := h.(StreamHandler1)
        BindStreamHandler1(h1)
    } else {
        h2 := h.(StreamHandler2)
        BindStreamHandler2(h2)
    }
}

But the signature of BindHandler becomes too weak :( I prefer using signature func BindHandler(h StreamHandler)

  • 写回答

1条回答 默认 最新

  • drduh44480 2018-12-01 10:37
    关注

    It seems that you are trying to design your classes using class hierarchies (like Java) which is really not how Go tackles OO. I really suggest you design your code around interfaces rather than trying to mimic inheritance. Since we cannot speculate on why you have such types, below is a minimal code snippet which will make BindHandler maintain a stricter signature.

    func BindHandler(h StreamHandler) {
        if Version == 1 {
            BindStreamHandler1(func(s Stream1) {
                h(s)
            })
        } else {
            BindStreamHandler2(func(s Stream2) {
                h(s)
            })
        }
    }
    

    Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解