go: Add documentation for golang interfaces (#1332)
* Add documentation for golang interfaces * Update go.md Co-authored-by: Rico Sta. Cruz <rstacruz@users.noreply.github.com>
This commit is contained in:
parent
c03aa5de51
commit
269c709c61
44
go.md
44
go.md
|
@ -581,6 +581,50 @@ By defining your receiver as a pointer (`*Vertex`), you can do mutations.
|
||||||
|
|
||||||
See: [Pointer receivers](https://tour.golang.org/methods/4)
|
See: [Pointer receivers](https://tour.golang.org/methods/4)
|
||||||
|
|
||||||
|
## Interfaces
|
||||||
|
|
||||||
|
### A basic interface
|
||||||
|
|
||||||
|
```go
|
||||||
|
type Shape interface {
|
||||||
|
Area() float64
|
||||||
|
Perimeter() float64
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Struct
|
||||||
|
|
||||||
|
```go
|
||||||
|
type Rectangle struct {
|
||||||
|
Length, Width float64
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Struct `Rectangle` implicitly implements interface `Shape` by implementing all of its methods.
|
||||||
|
|
||||||
|
### Methods
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (r Rectangle) Area() float64 {
|
||||||
|
return r.Length * r.Width
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Rectangle) Perimeter() float64 {
|
||||||
|
return 2 * (r.Length + r.Width)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The methods defined in `Shape` are implemented in `Rectangle`.
|
||||||
|
|
||||||
|
### Interface example
|
||||||
|
|
||||||
|
```go
|
||||||
|
func main() {
|
||||||
|
var r Shape = Rectangle{Length: 3, Width: 4}
|
||||||
|
fmt.Printf("Type of r: %T, Area: %v, Perimeter: %v.", r, r.Area(), r.Perimeter())
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## References
|
## References
|
||||||
|
|
||||||
### Official resources
|
### Official resources
|
||||||
|
|
Loading…
Reference in New Issue