Back to Gotraining

README

topics/go/language/methods/README.md

latest2.1 KB
Original Source

Methods

Methods are functions that give data the ability to exhibit behavior.

Notes

  • 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.

Quotes

"Methods are valid when it is practical or reasonable for a piece of data to expose a capability." - William Kennedy

Methods
Methods, Interfaces and Embedded Types in Go - William Kennedy
Escape-Analysis Flaws - William Kennedy

Code Review

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)

Exercises

Exercise 1

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.