Methods are functions that are declared with a receiver which binds the method to a type. Methods can be used to operate on values or pointers of that type.
- Methods are functions that declare a receiver variable.
- Receivers bind a method to a type and can use value or pointer semantics.
- Value semantics mean a copy of the value is passed across program boundaries.
- Pointer semantics mean a copy of the values address is passed across program boundaries.
- Stick to a single semantic for a given type and be consistent.
"Methods are valid when it is practical or reasonable for a piece of data to expose a capability." - William Kennedy
https://golang.org/doc/effective_go.html#methods
http://www.goinggo.net/2014/05/methods-interfaces-and-embedded-types.html
Declare and receiver behavior (Go Playground)
Value and Pointer semantics (Go Playground)
Named typed methods (Go Playground)
Function/Method variables (Go Playground)
Function Types (Go Playground)
Declare a struct that represents a baseball player. Include name, atBats and hits. Declare a method that calculates a players batting average. The formula is Hits / AtBats. Declare a slice of this type and initialize the slice with several players. Iterate over the slice displaying the players name and batting average.
Template (Go Playground) | Answer (Go Playground)
All material is licensed under the Apache License Version 2.0, January 2004.