topics/go/language/interfaces/README.md
Interfaces provide a way to declare types that define only behavior. This behavior can be implemented by concrete types, such as struct or named types, via methods. When a concrete type implements the set of methods for an interface, values of the concrete type can be assigned to variables of the interface type. Then method calls against the interface value actually call into the equivalent method of the concrete value. Since any concrete type can implement any interface, method calls against an interface value are polymorphic in nature.
"Polymorphism means that you write a certain program and it behaves differently depending on the data that it operates on." - Tom Kurtz (inventor of BASIC)
"The empty interface says nothing." - Rob Pike
"Design is the art of arranging code to work today, and be changeable forever." - Sandi Metz
"A proper abstraction decouples the code so that every change doesn’t echo throughout the entire code base." - Ronna Steinburg
Interfaces
The Laws of Reflection - Rob Pike
Methods, Interfaces and Embedded Types in Go - William Kennedy
Interface Pollution - JBD
Abstraction Considered Harmful - Tyler Treat
Interface Values Are Valueless - William Kennedy
Interface Semantics - William Kennedy
Hyrum's Law - Hyrum
Repetitive Code That Needs Polymorphism (Go Playground)
Polymorphism (Go Playground)
Method Sets (Go Playground)
Address Of Value (Go Playground)
Storage By Value (Go Playground)
Type Assertions (Go Playground)
Conditional Type Assertions (Go Playground)
The Empty Interface and Type Switches (Go Playground)
Storing Values (Go Playground)
Part A Declare an interface named speaker with a method named speak. Declare a struct named english that represents a person who speaks english and declare a struct named chinese for someone who speaks chinese. Implement the speaker interface for each struct using a value receiver and these literal strings "Hello World" and "你好世界". Declare a variable of type speaker and assign the address of a value of type english and call the method. Do it again for a value of type chinese.
Part B Add a new function named sayHello that accepts a value of type speaker. Implement that function to call the speak method on the interface value. Then create new values of each type and use the function.
Template (Go Playground) | Answer (Go Playground)
All material is licensed under the Apache License Version 2.0, January 2004.