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:
Luong Vo 2020-08-03 19:33:43 +07:00 committed by GitHub
parent c03aa5de51
commit 269c709c61
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 44 additions and 0 deletions

44
go.md
View File

@ -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)
## 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
### Official resources