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.