Trying to "translate" C++ base class methods to Go

I’m an experienced C++ programmer but utterly new to Go. I am trying to learn Go to try to decide if Go is for me. Perhaps my problem is that I am “thinking in C++.”

I have created my first application. It is a dummy graphics program. It implements four shapes (circle, square, etc.) each of which has a draw() method – total dummy – draw() consists of outputting a message “drawing a square at such and such an address.”

I have an interface called drawableshape with the draw() method, so all of my shapes are drawableshapes.

In C++ I would base all of these shapes on a base class that would have common members: variables and methods. In my Go program I have a shapebase struct that I incorporate into every shape. It has one var, a float64 position. (My drawing canvas is unidimensional ).

I would like to implement a move(increment float64) function. It would be the same for every shape – it would add the increment to the position. In C++ I would put that method into the base class and then every shape would inherit that single move() method. Obviously I can’t do exactly that in Go. What should I do instead? I can think of several solutions but they all seem overly verbose or complex.

  • Create an identical move() method for every shape, that either incremented the shapebase position itself, or called through to a move() method on shapebase. Seems like a lot of duplicate code.
  • Create a getbase() method in every shape, that would return the address of its shapebase struct. Then I could do something like mysquare.getbase().move(increment) . That seems overly complex, at least at this point where there is only one method on shapebase.

How should I be doing this in Go? I’m looking for “the right way” to address this sort of situation, not an answer to this one silly programming problem.

Is this what you’re looking for: https://play.golang.org/p/z8kJ50K11lr

2 Likes

Yes! Perfect! Thank you. Took me a while to figure out how your Circle implemented Move(). I’ve been learning Go from the tour on Golang.org and yourbasic.org/Golang and I don’t think that either one covered that you could “embed” one struct in another, and that then its members effectively became members of the outer or containing struct. That – to my C++ way of thinking – makes the inner struct “work like” a parent class. I will have to play with this and think about it a little. Thanks again.

To clarify, I inferred that I could embed in the Circle struct a named variable of type shapebase s shapebase but not that I could simply code shapebase and “incorporate” shapebase into Circle.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.