3 ms·
Weaker might have been the wrong word; it's more just different than anything else. Go struct embedding doesn't do much more than forward a method call to an in
by lbarrow 11y ago
Weaker might have been the wrong word; it's more just different than anything else. Go struct embedding doesn't do much more than forward a method call to an inner struct:
>There's an important way in which embedding differs from subclassing. When we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one. In our example, when the Read method of a bufio.ReadWriter is invoked, it has exactly the same effect as the forwarding method written out above; the receiver is the reader field of the ReadWriter, not the ReadWriter itself.
https://golang.org/doc/effective_go.html#embedding https://golang.org/doc/effective_go.html#embedding
- parenthephobia 11y agoI think the important thing isn't what happens internally, but what it looks like from the outside. Fundamentally, invoking a (non-virtual) superclass's method in C++ doesn't do much more than forward that method to an inner struct. struct Reader { int fd; } struct Writer { int fd; void Write (int) { // *this* points to the Writer, not the ReadWriter } } int writeForMe (Writer *w) { // *w* points to the Writer, not the ReadWriter } struct ReadWriter: Reader, Writer { } The only real difference, aside from the syntax, is that in C++ one can dynamically convert a pointer to a Writer that is part of a ReadWriter into a pointer to that ReadWriter, something Go doesn't support.