dss087358 2019-02-21 15:05
浏览 45

没有方法的多态性

Note: I'm editing this question to a concrete example of why I want to do this, which is why some of the answers might no longer make sense in context.

I am writing a bit of code that passes data from an input. The data is in the form of tags that have an identifier of what kind of data they contain and then the data.

Unfortunately I have no control over the input and don't know in advance what tags will be in it, one might be an int another might be a string, yet another might be an array of ints.

The problem arises when I need to handle all tags like the same type, for instance if I have a slice of tags, of a function that either accepts or returns a tag.

The solutions I have so far seen to this is to define the slices/functions with an empty interface which would allow me to do so, however that is kinda undesirable as it would not tell anything to other people using the package about what types are expected and also kinda defies the point of having a typed language in the first place.

Interfaces does however seem to be the solution here, and i would love to have a Tag interface to pass around, that does require though that I define methods on them, and there are really no methods they need.

My current solution looks like this

type Tag interface{
    implementTag()
}

type TagInt int
func (tag TagInt) implementTag() {}

type TagString string
func (tag TagInt) implementTag() {}

While this does indeed work and solves my problem, having to define dummy methods just for that feels very wrong.

So my question sums up in this: Are there any way that I can define that something is a Tag without having to define dummy methods?

  • 写回答

3条回答 默认 最新

  • doudao9915 2019-02-21 15:07
    关注

    You can use []interface{} for a "slice of any type" but then it's up to you to use type assertions and/or type switches to discover the actual runtime types of that slice's members.

    Learn more about empty interfaces in the Tour of Go


    And now want to make a slice that can hold both t1 and t2 but nothing else.

    This is quite an unusual requirement and you're unlikely to need this in Go. But you could also do your own discriminated union with:

    type item struct {
      typeSelector int
      t1Value t1
      t2Value t2
    }
    

    And then use []item, checking typeSelector at runtime to see which value is populated.

    Alternatively you could even use *t1 and *t2 and have nil signify "no value in this field".

    评论

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示