wiki/content/20200928193245-embedding.md

48 lines
945 B
Markdown
Raw Normal View History

2024-05-06 20:40:05 +00:00
---
2024-10-30 17:34:11 +00:00
date: 2020-09-28
2024-05-06 20:40:05 +00:00
id: 8f08356d-b0dc-465b-b7f5-5522b5133916
title: Golang Embedding
---
# Description
[Embedding](https://golang.org/doc/effective_go.html#embedding) is Gos
answer to subclasses. There's one caveat:
> 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.
# Interfaces
``` go
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
type ReadWriter interface {
Reader
Writer
}
```
`ReadWriter` "extends" `Reader` & `Writer` in the example above.
# Structs
``` go
type ReadWriter struct {
*Reader // *bufio.Reader
*Writer // *bufio.Writer
}
func (rw *ReadWriter) Read(p []byte) (n int, err error) {
return rw.reader.Read(p)
}
```