Go Interfaces: Difference between revisions
Line 28: | Line 28: | ||
=Initialization= | =Initialization= | ||
=Passing Interfaces to Functions= | |||
Interface instances can be used as arguments to functions. | |||
A ''pointer'' to the interface instance can be passed as argument to a function after declaring that the function accepts a parameter of that interface type in the function signature. | |||
Passing an interface pointer insures that the function body can rely on the fact the interface methods are available on the passed instance. | |||
<blockquote style="background-color: Gold; border: solid thin Goldenrod;"> | |||
:When passing an interface to a function, you should always pass a pointer to the instance implementing the interface, not the value of the instance implementing the interface.<br> | |||
</blockquote> |
Revision as of 17:55, 30 March 2016
Internal
Overview
An interface is a type declaration that defines a method set.
A method set is a list of methods a type must have in order to implement the interface. A type (struct, anything else?) implements an interface implicitly, doing nothing else but exposing all methods from the interface's method set. "Exposing" in this context means the methods in question was declared to use the type as receiver. This is called duck typing. There is no "implements" or "extends" keyword in Go.
Interface instances can be used as arguments to functions. See passing interfaces to functions.
- Can only structs be interfaces, or there are other things that can be interfaces?
Declaration
The interface declaration is introduced by the type keyword, to indicated that this is a user-defined type, followed by the interface name and the keyword interface. Unlike in the struct's case, we don't define fields but a method set.
type MyInterface interface { functionName1() return_type functionName2() return_type ... }
Initialization
Passing Interfaces to Functions
Interface instances can be used as arguments to functions.
A pointer to the interface instance can be passed as argument to a function after declaring that the function accepts a parameter of that interface type in the function signature.
Passing an interface pointer insures that the function body can rely on the fact the interface methods are available on the passed instance.
- When passing an interface to a function, you should always pass a pointer to the instance implementing the interface, not the value of the instance implementing the interface.