-1

How can I avoid implicit cast in Go?

for example:

type runner interface {
    run()
}

type person struct {
}

type program struct {
}

func (p person) run()  {}
func (p program) run() {}

If my intention of runner is only for person, not a program? as you know, both person and program implements(satisfy) the runner interface.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
mohammad
  • 2,568
  • 3
  • 20
  • 41
  • 3
    Add another, "marker" method to `runner`, e.g. `implementsRunner()`. See [What is the idiomatic way in Go to create a complex hierarchy of structs?](https://stackoverflow.com/questions/29144622/what-is-the-idiomatic-way-in-go-to-create-a-complex-hierarchy-of-structs/29145086?r=SearchResults#29145086) – icza Feb 06 '21 at 15:17
  • 1
    A note on terminology: Go doesn't do type casting at all, implicit or otherwise. – Jonathan Hall Feb 06 '21 at 15:24
  • 1
    Erm... it kind of defeats the point of go's interface system, and this example is a hypothetical, but if your `runner` type is something akin to java's runnable interface, there's bound to be other methods that differentiate the two. A program must have IO, whereas a _"runner"_ could just be a thread (routine), which either doesn't communicate, or uses channels or whatever. – Elias Van Ootegem Feb 06 '21 at 19:12
  • 1
    A question to ask that can help you differentiate: do both methods really make sense as having no return value? For example, when running a program, it might return a status code on completion. You can make a custom type for this status code so that an unrelated "run" method will have no reason to overlap. – Hymns For Disco Feb 06 '21 at 20:57

1 Answers1

1

There is no implicit casting. Both structs satisfy runner, so both structs are able to be that interface.

If you are doing some conditional and you want to split person and program, you can always implement an additional method that only person will implement, but program will not. Such as this (playground)

type runner interface {
    isRunner() bool
    run()
}

You might want to see this GoByExample page which links to a great blog post at the bottom describing what interfaces are and how to use them.

Steven Masley
  • 634
  • 2
  • 9