Go Interfaces: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(293 intermediate revisions by the same user not shown)
Line 1: Line 1:
=External=
* https://go.dev/ref/spec#Interface_types
=Internal=
=Internal=
* [[Go Language]]
* [[Go_Language_Object_Oriented_Programming#Interfaces|Object-Oriented Programming in Go]]
=Overview=
An '''interface''' is a set of method signatures. The interface is declared with the keyword <code>[[Go_Language#type_keyword|type]]</code>, followed by the name of the interface, followed by the keyword <code>[[Go_Language#interface_keyword|interface]]</code> and by the method signatures enclosed in a curly brace block. Each signature contains the method name, optional parameter names and mandatory parameter types, and optional return variable names and mandatory return types. Providing parameter and return names is recommended, as it arguably exposes more semantics, making the code clearer. See [[#Declaration|example]], below. There are no method implementations.
Interfaces are not fully-featured types, they're less than that, but they're used to express conceptual similarities between types. If several types implement the same interface, they are similar in a way that is important to the application. An interface highlights the similarities between the types implementing it and conceals the differences.
Interfaces are not declared to be satisfied, they are satisfied implicitly.  A type '''implements''' (or '''satisfies''') an interface if the type defines '''all''' methods specified in the interface. Of course, the type can have other methods not specified by the interface.
Interfaces can be thought of a kind of conceptual inheritance (types inherit behavior specified by an interface) and help with implementing [[Go_Language_Object_Oriented_Programming#Polymorphism|polymorphism]] in Go.
"The bigger the interface, the weaker the abstraction." The most important thing about interfaces in Go is that the smaller the interface is, the more useful it is. This is a Go-specific idea: we want to make little interfaces, so we can build components that share them.
Go type system is structural,  not nominal. The interfaces are behavior contracts, and they belong in the consuming code, not in the producing code. A common pattern should be to accept interfaces and return structs.
Interfaces are defined at the "fault lines" of the system's architecture. These are between the <code>main()</code> function and the rest, and along the package API boundaries. Interfaces should not be defined before a realistic example of usage exists.
Interfaces are rigid. For a library that exposes interfaces in the public API, any change to the interface requires releasing a new major version, since it breaks all third-party implementations.
=Declaration=
The following syntax declares an interface:
<syntaxhighlight lang='go'>
type <Interface_Name> interface {
  <method_signature_1>
  <method_signature_2>
  ...
}
</syntaxhighlight>
Example:
<syntaxhighlight lang='go'>
type SomeInterface interface {
  MethodA(int) (int, error)                          // No parameter and return value names are specified.
  MethodB(someValue int) (someResult int, err error) // Parameter and return value names are provided.
                                                    // This is arguably clearer, as it conveys more semantics.
}
</syntaxhighlight>
What results after such a declaration is an <span id='Interface_Type'></span>'''interface type'''. For a discussion of concrete type vs. interface types, see: {{Internal|Go_Language#Concrete_vs._Interface_Types|Go Language &#124; Concrete vs. Interface Types}}
=Idiomatic Interface Conventions=
Single-method interfaces are named using the method name plus an "er" suffix. An interface with just one <code>Write</code> method would be called <code>Writer</code>.
Also see: {{Internal|Go_Style#Naming|Go Style}}
=Implementing an Interface=
As mentioned [[#Overview|above]], interfaces are not formally declared to be satisfied with dedicated syntax, they are satisfied implicitly. The type satisfying an interface do not need to formally declare the name of the interface anywhere in its definition. Instead, it is sufficient to declare themselves as [[Go_Language_Object_Oriented_Programming#Value_Receiver_Type|value]] or [[Go_Language_Object_Oriented_Programming#Pointer_Receiver_Type|pointer receiver types]] for '''all''' the methods in the interface declaration.
<syntaxhighlight lang='go'>
type SomeImplementation { ... } // SomeInterface is specified nowhere in the SomeImplementation declaration
// Declaring the type as pointer receiver for *all* methods declared in the interface makes the type
// to implement that interface . Value and pointer receivers must not be mixed by the method
// implementations of an interface
func (s *SomeImplementation) MethodA(i int) (int, error) { ... }
func (s *SomeImplementation) MethodB(someValue int) (int, error) { ... }
</syntaxhighlight>
=Interface Values=
Declaring a variable of an interface type creates an '''interface value'''.


* [[Go Concepts - The Type System#User-Defined_Types|The Type System]]
The interface value is a pair that contains a '''dynamic type''' and a '''dynamic value'''. The dynamic type is a [[Go_Language#Concrete_Type|concrete type]] that implements that interface. The dynamic value is an instance of the dynamic type:
<syntaxhighlight lang='go'>
var i SomeInterface // i is a pair: (dynamic_type, dynamic_value)
</syntaxhighlight>


=Overview=
Assuming the following interface and concrete type declarations:
<syntaxhighlight lang='go'>
type SomeInterface interface {
  MethodA()
}
 
type SomeImplementation struct {
  data string
}
 
// MethodA makes SomeImplementation implement the interface.
func (s *SomeImplementation) MethodA() {
  if s != nil {
    fmt.Printf("data: %s\n", s.data)
  } else {
    fmt.Println("invocation with a nil dynamic value")
  }
}</syntaxhighlight>
... the following variable declarations and initializations create an interface variable and a concrete type variable. The code then assigns the interface variable with the concrete type variable, which will make the interface value get the pair of a dynamic type (<code> SomeImplementation </code>) and the dynamic value (<code>t</code>):
<syntaxhighlight lang='go'>
var i SomeInterface
var t *SomeImplementation
t = &SomeImplementation{"blue"}
i = t
</syntaxhighlight>
The interface value can be then used to invoke the method on the dynamic concrete type instance (the dynamic value).
<syntaxhighlight lang='go'>
i.MethodA() // prints "data: blue"
</syntaxhighlight>
An interface value can have a <code>nil</code> dynamic value, and still be usable, as long it is assigned a dynamic type with this syntax:
<syntaxhighlight lang='go'>
var i SomeInterface
var t *SomeType // Declares "t" a pointer to the concrete type, not the concrete type
i = t
</syntaxhighlight>
An interface value assigned with a pointer to the dynamic type, but not with a dynamic value can still be invoked into, given that the method implementation cases for the situation when the receiver type [[Go_Language_Object_Oriented_Programming#Implicit_Argument|implicit argument]] is <code>nil</code>. In the example above, we assigned <code>i</code> a dynamic type, <code>SomeImplementation</code>, but not a dynamic value, as <code>t</code> has no concrete value yet. The dynamic type is enough information to go find which implementation <code>MethodA()</code> should use. That is why it is a good idea to guard against <code>nil</code> implicit argument in all concrete methods provided by types that implement interfaces. This way you have a static (in the Java or Python sense of the word) method and an instance method at the same time.
<syntaxhighlight lang='go'>
i.MethodA() // prints "invocation with a nil dynamic value"
</syntaxhighlight>
An interface value that carries a dynamic type but no dynamic value is a legal state. It is a way to implement static (type) methods.
==<tt>nil</tt> Interface Value==
This describes an interface value with a <code>nil</code> dynamic type. In this situation, you cannot call the methods on that interface, because without a dynamic type you can't know which method you are referring to.
 
=<span id='Interfaces_as_Function_Parameters_and_Return_Values'></span>Interfaces as Function Parameters and Result Values=
==Interface as Function Parameter==
When a function is declared with a parameter that has an interface type, the function can be invoked with either a value or a pointer of the implementing type, as long the implementation uses a value receiver type. For the following interface and type declaration:
<syntaxhighlight lang='go'>
type SomeInterface interface {
    MethodA()
}
 
type SomeImplementation struct {
    data string
}
</syntaxhighlight>
the type may chose to implement the interface by using a value receiver:
<syntaxhighlight lang='go'>
func (s SomeImplementation) MethodA() {
    fmt.Printf("data: %s\n", s.data)
}
</syntaxhighlight>
 
In this case, if a function is declared with a parameter of <code>SomeInterface</code> interface type, the function can be invoked by passing either a value or a pointer to the type instance:
 
<syntaxhighlight lang='go'>
func SomeFunc(i SomeInterface) {
    i.MethodA()
}
 
...
 
t := SomeImplementation{data: "blue"}
SomeFunc(t)
 
// this also works:
t2 := &SomeImplementation{data: "red"}
SomeFunc(t2)
</syntaxhighlight>
 
If the implementation of the interface is done with a pointer receiver:
<syntaxhighlight lang='go'>
func (s *SomeImplementation) MethodA() {
    fmt.Printf("data: %s\n", s.data)
}
</syntaxhighlight>
 
then only a pointer to the implementing type instance can be passed to the function <code>SomeFunc()</code>:
 
<syntaxhighlight lang='go'>
t := &SomeImplementation{data: "green"}
SomeFunc(t)
</syntaxhighlight>
 
If we attempt to pass an implementing type instance value, the compiler complains:
<font size=-2>
Cannot use t (variable of type SomeImplementation) as SomeInterface value in argument to SomeFunc: SomeImplementation does not implement SomeInterface (method MethodA has pointer receiver)
</font>
 
==Interface as Function Result==
Functions can return interfaces as results:
 
<syntaxhighlight lang='go'>
type SomeInterface interface {
  ...
}
 
type SomeImplementation struct {
  ...
}
 
// the type SomeImplementation  is presumably declared as receiver type for all interface methods, thus implements it
 
func someFunc() SomeInterface {
  return &TheImplementation{} // this is a valid function declaration
}
</syntaxhighlight>
 
=<span id='Empty_Interface'></span><span id='any'></span>Empty Interface <tt>interface{}</tt> <tt>any</tt>=
An empty interface, declared as <code>interface{}</code> or <code>any</code> is an interface that specifies no methods. Any type can "implement" that interface. If you want to declare a parameter of any type for a function, make it an empty interface:
<syntaxhighlight lang='go'>
func SomeFunc(v interface{}) {
  ...
}
</syntaxhighlight>
<syntaxhighlight lang='go'>
func SomeFunc(v any) {
  ...
}
</syntaxhighlight>
According to the <code>builtin</code> package documentation, <code>any</code> is an alias for <code>interface{}</code> and it is equivalent to <code>interface{}</code> in all ways.
 
Rob Pike does not like empty interfaces: when you're programming and you use an empty interface, think really hard if this is actually what you want, or whether isn't just a little something you can put in, an interface with an actual method that is really necessary to capture the things you are talking about.
 
=Using Interfaces=
==Function with Multiple Types of Parameters==
Interface expresses similarity, so make the function take as a parameter an interface that expresses the similarity of all desired arguments.
<syntaxhighlight lang='go'>
func Area(s Shape) {
  ...
}
</syntaxhighlight>
=Type Assertions=
{{Internal|Go Type Assertions#Overview|Type Assertions}}
=Mocking=
See: {{Internal|Github.com/stretchr/testify#Mocks|Testify Mocks}}
=<span id='Embedded_Type'></span>Embedded Types=
Interface names can be used as [[Go_Structs#Embedded_Type|embedded types]] in structs.
 
=TO DEPLETE=
 
<font color=darkkhaki>
==Overview==
 
Go has an unique interface system that allows programs to model behavior rather than model types: the behavior is "attached" to types via methods, and, independently, the behavior contract is defined by interfaces. The fact that a type implements an interface is not formally declared via a keyword, like in Java, or otherwise, but is an implicit consequence of a type "having" all the behavior declared by the interface. This is called [[Programming_Languages_Concepts#Duck_Typing|duck typing]]. If a type implements an interface by the virtue of duck typing, a value of the type can be stored in a value of that interface type and the compiler ensure the assignments are correct at compile-time.
 
:''<span id="duck_typing_does_not_help_readability">Is this a good thing? As far as I can tell, I can't say whether a specific type implements an interface, short of browsing all methods in the package, looking for receivers of that specific type. The compiler does that easily, but I don't. This does not help code readability.</span>''


Go has an unique interface system that allows modeling behavior rather than modeling types. An interface declares the behavior of a type. The availability of interfaces in the language allows for [[Programming#Polymorphism|polymorphism]].
A type and its associated [[Go_Concepts_-_The_Type_System#Pointer_Types|pointer type]] may or may not implement the same interface, depending on how the methods are "associated" with the value and pointers of that type. In order to understand how a type or its corresponding pointer type implements an interface, you need to understand [[#Method_Sets|method sets]], which will be explained below. The notion of a type implementing an interface is related to method set inclusion. For more details see "[[Go_Interfaces#When_does_a_Type.2FPointer_Type_Implement_an_Interface.3F|When does a type/pointer type implement an interface?]]" below.


There is no need to declare that an interface is implemented, the compiler does the work of determining whether the values of a type satisfy an interface. ''Is this a good thing? As far as I can tell, I can't say whether a specific type implements an interface, short of browsing all methods in the package, looking for receivers of that specific type. This does not help code readability.'' So, if a type implements the methods of an interface, a value of the type can be stored in a value of that interface type and the compiler ensure the assignments are correct at compile-time.
Any used-defined named type ([[Go Structs|structs]], [[Go Type Aliasing|aliased types]]) can be made to implement interfaces.


If a method call is made against an interface value, the equivalent method of the stored user-defined value - whatever that happens to be at the moment - it is executed. This is an expression of the polymorphic nature of the language. The user-defined type is often called a ''concrete type''.
The fact that Go detaches the contract from implementation with interfaces allows for [[Programming_Languages_Concepts#Polymorphism|polymorphism]]. Wen a method call is made against an interface value, the equivalent method of the stored user-defined type value it is executed. The user-defined type that implements an interface is often called a ''concrete type'' for that interface.


Interfaces in Go tend to be small, exposing only a few functions, or just one function.
Interfaces in Go tend to be small, exposing only a few functions, or just one function.


<font color=red>
==Method Sets==
'''TODO'''


* Can only structs be interfaces, or there are other things that can be interfaces? "Go in Action" mentions ''named types''.
A type may have a ''method set'' associated with it.  
* It seems that the values and pointers are interchangeable when used as interface - we can pass a value or a pointer when we invoke an interface method and the compiler will be fine.
* [[Go_Concepts_-_Functions#Receivers_and_Interfaces]]
* [[Go_Concepts_-_Functions#Receiver_Best_Practice]]
</font>


=Method Sets=
There are two kinds of method sets: [[#Interface_Method_Set|interface method sets]] and [[#User-Defined_Type_Method_Set|user-defined types method sets]]. In the case of user-defined type method set, there's a distinction between the type method set and the pointer type method set, as it will be shown below.


Each type has a ''method set'' associated with it. There are [[#Interface_Method_Set_and_the_Interface_Type_Declaration|interface method sets]] and [[#User-Defined_Type_Method_Set|user-defined types method sets]].  
If a type does not have any of the previously mentioned method sets, it is said to have an empty method set.


In a method set, each method must have a unique non-blank method name.
In a method set, each method must have a unique non-blank method name.


The language specification defines the method sets here [https://golang.org/ref/spec#Method_sets here].
The language specification defines the method sets here: https://golang.org/ref/spec#Method_sets.


==Interface Method Set and the Interface Type Declaration==
===Interface Method Set===


===Interface Type===
An ''interface method set'' is a list of method declarations (function name and signature), specified in the [[#Interface_Type|interface type declaration]]. The interface type declaration has the only purpose of defining the method set and giving it a name - the interface name.
 
The method set only contains method names and signatures, so the interface type does not define ''how'' the behavior is implemented, but just the behavior's contract. The interfaces allow us to hide the incidental details of the implementation. The behavior implementation details are contained by user-defined types, via methods.
 
Also, the method signatures from the interface method set are independent on whether the corresponding methods from the concrete types are declared with value or pointer receivers.
 
====Interface Type====


An ''interface type'' is a user-defined type whose only purpose is to introduce a method set (the [[#Interface_Method_Set|interface method set]]) and to give it a name.
An ''interface type'' is a user-defined type whose only purpose is to introduce a method set (the [[#Interface_Method_Set|interface method set]]) and to give it a name.


The interface type declaration starts with the <tt>type</tt> keyword, to indicated that this is a user-defined type, followed by the interface name and the keyword <tt>interface</tt>, followed by the interface method set declaration between curly braces. Unlike in the <tt>struct</tt>'s case, we don't define fields.
The interface type declaration starts with the <tt>type</tt> keyword, to indicated that this is a user-defined type, followed by the interface name and the keyword <tt>interface</tt>, followed by the interface method set declaration between curly braces. The interface method set declaration consists in a list of method names followed by their [[Go_Concepts_-_Functions#Function_Signature|signatures]]. Unlike in the <tt>struct</tt>'s case, we don't define fields.


<pre>
<pre>
Line 58: Line 283:
</pre>
</pre>


===Interface Method Set===
====Interface Name Convention====
 
If the interface type contains only one method, the name of the interface starts with name of the method and ends with the ''er'' suffix. When multiple methods are declared within an interface type, the name of the interface should relate to its general behavior.
 
====Interface====
 
The method set of an interface type it is said to be the type's ''interface''.
 
===User-Defined Type Method Set===
 
====Method Set associated with the Values of a Type====


An ''interface method set'' is the specified in the interface type declaration. The interface type declaration has the only purpose of defining the method set and giving it a name - the interface name.
The method set associated with the values of a type consists of all methods declared with a ''value receiver'' of that type.


The specification defines ''the method set of a type'' as the method set associated with the values of the type.


===Interface===
====Method Set associated with the Pointers of a Type====


The method set associated with the pointers of a type <tt>T</tt> consists of both all methods declared with a pointer receiver <tt>*T</tt> ''and'' with a value receiver <tt>T</tt>.


The method set associated with the pointers of a type always includes the method set associated with the values of the type. This is because given a pointer, we can always infer the value pointed by that address, so the methods associated with the value will naturally "work". The reverse is not true - given a value, not always we can get an address for it, and because we are not able to get an pointer, we cannot assume that the methods associated with the pointer will work. [https://github.com/NovaOrdis/playground/tree/master/go/reference This is an example that demonstrates that we cannot always get an address for a value].


The method set is a list of method signatures designating methods a type must expose in order to ''implement'' the interface. See [[#Making_a_Type_Implement_an_Interface|making a type implement an interface]].  
Another way of expressing this is that pointer receiver method are ''less general'' than the value receiver methods: value receiver methods can ''always'' be used, pointer receiver methods can't always be used.


The method set contains method signatures, so the interface type does not define ''how'' the behavior is implemented, but just the behavior's contract. The interfaces allow us to hide the incidental details of the implementation. The behavior implementation details are contained by user-defined types, via methods.
Also see:


===Interface Name Convention===
<blockquote style="background-color: #f9f9f9; border: solid thin lightgrey;">
:[[Go_Concepts_-_Functions#Receivers_and_Interfaces|Receivers and Interfaces]]
</blockquote>


If the interface type contains only one method, the name of the interface starts with name of the method and ends with the ''er'' suffix.
==When does a Type/Pointer Type Implement an Interface?==


When multiple methods are declared within an interface type, the name of the interface should relate to its general behavior.
Note that notion of a type implementing an interface and its corresponding pointer type implementing the same interface both make sense, and they are subtly different.


==User-Defined Type Method Set==
According to the language specification, a user-defined type <tt>T</tt> implements an interface if its [[#User-Defined_Type_Method_Set|method set]] (all methods declared with ''a value receiver'' of type <tt>T</tt>) is a superset of the [[#Interface|interface]].


The method set of a user-defined type <tt>T</tt> consists of all methods declared with a receiver of that type <tt>T</tt>.  
By extrapolation, a pointer type implements an interface when the method set associated with pointers to that type is a superset of the [[#Interface|interface]]. As per [[Go_Interfaces#User-Defined_Type_Method_Set|User-Defined Type Method Set]] section, the method set associated with the pointer of a type include implicitly the method set associated with the value of the type.  


The method set of the corresponding pointer type <tt>*T</tt> is the set of all methods declared with receiver <tt>*T</tt> or <tt>T</tt>. The method set of the corresponding pointer type always includes by default the methods declared with the value receiver of the type.
For more details about value and pointer receivers, see:


=When does a Type implement an Interface?=
<blockquote style="background-color: #f9f9f9; border: solid thin lightgrey;">
:[[Go_Concepts_-_Functions#Value_and_Pointer_Receivers|Value and Pointer Receivers]]
</blockquote>


=Making a Type Implement an Interface=
For more details about pointer types see:


A type (<tt>struct</tt>, <font color=red>anything else?</font>) can be made to implement an interface by making the type to expose all methods from the interface's method set. "Exposing" a method means that a method with the same name and signature [[Go_Concepts_-_Functions#Receivers|is declared to use the type in question as value or pointer receiver]].
<blockquote style="background-color: #f9f9f9; border: solid thin lightgrey;">
:[[Go_Concepts_-_The_Type_System#Pointer_Types|Pointer Types]]
</blockquote>


This is called [[Programming#Duck_Typing|duck typing]]. There is no "implements" or "extends" keyword in Go.
==Example==


The example that follows shows how a type <tt>B</tt> implements interface <tt>A</tt>:
The example that follows shows how a type <tt>B</tt> implements interface <tt>A</tt>:
Line 95: Line 339:
<pre>
<pre>
//
//
// The interface A declares a method set containing a single method m()
// The interface A declares an interface method set containing a single method m()
//
//
type A interface {
type A interface {
Line 102: Line 346:


//
//
// At this point, the struct B is not yet linked to the interface A in any  
// At this point, the type B is not yet linked to the interface A in any way.
// way (it does not implement interface A)
// Its method set is empty, so it does not implement interface A, it does not
// implement any interface.
//
//
type B struct {
type B struct {
Line 110: Line 355:


//
//
// We make B implement interface A by declaring B as a value receiver for  
// We make B implement interface A by declaring B as a value receiver for m().
// m(). Pointer receiver also works. Since A only contains m(), B implements
// This means B's method set includes now m() and it is a superset of A's method
// A by the virtue of duck typing
// set.
//
//
func (b B) m() {
func (b B) m() {
Line 122: Line 367:


//
//
// B now implements A, so A methods can be invoked on B
// B now implements A, so B instances can be assigned to A variables
//
//
b := B{1}
var a A
b.m()
a = B{1}
a.m()
 
//
// *B now also implements A, because the method set of the pointer type
// includes the methods declared agains the value  so *B instances
// can be assigned to A variables
//
var a2 A
a2 = &B{2}
a2.m()


...
...
</pre>
</pre>


Interface instances can be used as arguments to functions. See [[#Passing_Interfaces_to_Functions|passing interfaces to functions]].
===A Variation of the Example===
 
Note that if in the example above we declare
 
<pre>
func (b *B) m() {
    ...
}
</pre>
 
instead of
 
<pre>
func (b B) m() {
    ...
}
</pre>
 
then the <tt>a = B{1}</tt> assignment would fail to compile with:


=Passing Interfaces to Functions=
<pre>
./main.go:23: cannot use B literal (type B) as type A in assignment:
B does not implement A (m method has pointer receiver)
</pre>
 
This is because the type B does not implement the interface, because m() is not in the type B method set.
 
However, if we try:
<pre>
var a A
a = &B{1}
a.m()
</pre>
 
it works in both cases, because the method set associated with the B pointers include both <tt>func (b B) m() ...</tt> and <tt>func (b *B) m() ...</tt> so the pointer type B implements the interface.
 
==Passing Interfaces to Functions==


Interfaces can be used as arguments to functions. Passing an interface instance insures that the function body can rely on the fact the interface methods are available on the passed instance.  
Interfaces can be used as arguments to functions. Passing an interface instance insures that the function body can rely on the fact the interface methods are available on the passed instance.  
Line 140: Line 429:
<pre>
<pre>
...
...
type A interface {
    m()
}
func (b B) m() {
    ...
}


func f(a A) {
func f(a A) {
Line 151: Line 448:
</pre>
</pre>


Note that the B instance can be passed by value (as in the example above) or by reference (as in the example below). Both cases work:
Note that the B instance can be passed by value (as in the example above) or by reference (as in the example below). Both cases work for reasons explained in the [[#Method_Set_associated_with_the_Pointers_of_a_Type|Method Set associated with the Pointers of a Type]] section:


<pre>
<pre>
Line 169: Line 466:
</pre>
</pre>


<font color=red>'''TODO''' further discussion on the merits of passing the interface by value and by reference.</font>
==Interfaces as Fields==


=Interfaces as Fields=
Interfaces can be used as [[Go_Structs#Fields|fields]] in <tt>[[Go_Structs|struct]]</tt>s.


Interfaces can be used as [[Go_Structs#Fields|fields]].
==Implementation Details==
 
=Implementation Details=


An interface variable is a two-word data structure.  
An interface variable is a two-word data structure.  


The first word contains a pointer to an internal table called ''iTable'', which contains type information about the stored value: the type of the value that has been stored (the concrete type) and a list of methods associated with the value.  
The first word contains a pointer to an internal table called ''iTable'', which contains type information about the stored value: the concrete type of the value that has been stored and a list of methods associated with the value. The second word is a reference to the stored value.
 
The second word is a reference to the stored value.


The combination of type information and pointer binds the relationship between the two values.
The combination of type information and pointer binds the relationship between the two values.


More details "Go in Action" page 125.
DEPLETE: [[Go Concepts - The Type System]]

Latest revision as of 23:45, 20 March 2024

External

Internal

Overview

An interface is a set of method signatures. The interface is declared with the keyword type, followed by the name of the interface, followed by the keyword interface and by the method signatures enclosed in a curly brace block. Each signature contains the method name, optional parameter names and mandatory parameter types, and optional return variable names and mandatory return types. Providing parameter and return names is recommended, as it arguably exposes more semantics, making the code clearer. See example, below. There are no method implementations.

Interfaces are not fully-featured types, they're less than that, but they're used to express conceptual similarities between types. If several types implement the same interface, they are similar in a way that is important to the application. An interface highlights the similarities between the types implementing it and conceals the differences.

Interfaces are not declared to be satisfied, they are satisfied implicitly. A type implements (or satisfies) an interface if the type defines all methods specified in the interface. Of course, the type can have other methods not specified by the interface.

Interfaces can be thought of a kind of conceptual inheritance (types inherit behavior specified by an interface) and help with implementing polymorphism in Go.

"The bigger the interface, the weaker the abstraction." The most important thing about interfaces in Go is that the smaller the interface is, the more useful it is. This is a Go-specific idea: we want to make little interfaces, so we can build components that share them.

Go type system is structural, not nominal. The interfaces are behavior contracts, and they belong in the consuming code, not in the producing code. A common pattern should be to accept interfaces and return structs.

Interfaces are defined at the "fault lines" of the system's architecture. These are between the main() function and the rest, and along the package API boundaries. Interfaces should not be defined before a realistic example of usage exists.

Interfaces are rigid. For a library that exposes interfaces in the public API, any change to the interface requires releasing a new major version, since it breaks all third-party implementations.

Declaration

The following syntax declares an interface:

type <Interface_Name> interface {
  <method_signature_1>
  <method_signature_2>
  ...
}

Example:

type SomeInterface interface {

  MethodA(int) (int, error)                          // No parameter and return value names are specified.
  MethodB(someValue int) (someResult int, err error) // Parameter and return value names are provided.
                                                     // This is arguably clearer, as it conveys more semantics.
}

What results after such a declaration is an interface type. For a discussion of concrete type vs. interface types, see:

Go Language | Concrete vs. Interface Types

Idiomatic Interface Conventions

Single-method interfaces are named using the method name plus an "er" suffix. An interface with just one Write method would be called Writer.

Also see:

Go Style

Implementing an Interface

As mentioned above, interfaces are not formally declared to be satisfied with dedicated syntax, they are satisfied implicitly. The type satisfying an interface do not need to formally declare the name of the interface anywhere in its definition. Instead, it is sufficient to declare themselves as value or pointer receiver types for all the methods in the interface declaration.

type SomeImplementation { ... } // SomeInterface is specified nowhere in the SomeImplementation declaration

// Declaring the type as pointer receiver for *all* methods declared in the interface makes the type 
// to implement that interface . Value and pointer receivers must not be mixed by the method 
// implementations of an interface
func (s *SomeImplementation) MethodA(i int) (int, error) { ... }
func (s *SomeImplementation) MethodB(someValue int) (int, error) { ... }

Interface Values

Declaring a variable of an interface type creates an interface value.

The interface value is a pair that contains a dynamic type and a dynamic value. The dynamic type is a concrete type that implements that interface. The dynamic value is an instance of the dynamic type:

var i SomeInterface // i is a pair: (dynamic_type, dynamic_value)

Assuming the following interface and concrete type declarations:

type SomeInterface interface {
  MethodA()
}

type SomeImplementation struct {
  data string
}

// MethodA makes SomeImplementation implement the interface.
func (s *SomeImplementation) MethodA() {
  if s != nil {
    fmt.Printf("data: %s\n", s.data)
  } else {
    fmt.Println("invocation with a nil dynamic value")
  }
}

... the following variable declarations and initializations create an interface variable and a concrete type variable. The code then assigns the interface variable with the concrete type variable, which will make the interface value get the pair of a dynamic type ( SomeImplementation ) and the dynamic value (t):

var i SomeInterface
var t *SomeImplementation
t = &SomeImplementation{"blue"}
i = t

The interface value can be then used to invoke the method on the dynamic concrete type instance (the dynamic value).

i.MethodA() // prints "data: blue"

An interface value can have a nil dynamic value, and still be usable, as long it is assigned a dynamic type with this syntax:

var i SomeInterface
var t *SomeType // Declares "t" a pointer to the concrete type, not the concrete type
i = t

An interface value assigned with a pointer to the dynamic type, but not with a dynamic value can still be invoked into, given that the method implementation cases for the situation when the receiver type implicit argument is nil. In the example above, we assigned i a dynamic type, SomeImplementation, but not a dynamic value, as t has no concrete value yet. The dynamic type is enough information to go find which implementation MethodA() should use. That is why it is a good idea to guard against nil implicit argument in all concrete methods provided by types that implement interfaces. This way you have a static (in the Java or Python sense of the word) method and an instance method at the same time.

i.MethodA() // prints "invocation with a nil dynamic value"

An interface value that carries a dynamic type but no dynamic value is a legal state. It is a way to implement static (type) methods.

nil Interface Value

This describes an interface value with a nil dynamic type. In this situation, you cannot call the methods on that interface, because without a dynamic type you can't know which method you are referring to.

Interfaces as Function Parameters and Result Values

Interface as Function Parameter

When a function is declared with a parameter that has an interface type, the function can be invoked with either a value or a pointer of the implementing type, as long the implementation uses a value receiver type. For the following interface and type declaration:

type SomeInterface interface {
    MethodA()
}

type SomeImplementation struct {
    data string
}

the type may chose to implement the interface by using a value receiver:

func (s SomeImplementation) MethodA() {
    fmt.Printf("data: %s\n", s.data)
}

In this case, if a function is declared with a parameter of SomeInterface interface type, the function can be invoked by passing either a value or a pointer to the type instance:

func SomeFunc(i SomeInterface) {
    i.MethodA()
}

...

t := SomeImplementation{data: "blue"}
SomeFunc(t)

// this also works:
t2 := &SomeImplementation{data: "red"}
SomeFunc(t2)

If the implementation of the interface is done with a pointer receiver:

func (s *SomeImplementation) MethodA() {
    fmt.Printf("data: %s\n", s.data)
}

then only a pointer to the implementing type instance can be passed to the function SomeFunc():

t := &SomeImplementation{data: "green"}
SomeFunc(t)

If we attempt to pass an implementing type instance value, the compiler complains:

Cannot use t (variable of type SomeImplementation) as SomeInterface value in argument to SomeFunc: SomeImplementation does not implement SomeInterface (method MethodA has pointer receiver)

Interface as Function Result

Functions can return interfaces as results:

type SomeInterface interface {
  ...
}

type SomeImplementation struct {
  ... 
}

 // the type SomeImplementation  is presumably declared as receiver type for all interface methods, thus implements it 

func someFunc() SomeInterface {
  return &TheImplementation{} // this is a valid function declaration
}

Empty Interface interface{} any

An empty interface, declared as interface{} or any is an interface that specifies no methods. Any type can "implement" that interface. If you want to declare a parameter of any type for a function, make it an empty interface:

func SomeFunc(v interface{}) {
  ...
}
func SomeFunc(v any) {
  ...
}

According to the builtin package documentation, any is an alias for interface{} and it is equivalent to interface{} in all ways.

Rob Pike does not like empty interfaces: when you're programming and you use an empty interface, think really hard if this is actually what you want, or whether isn't just a little something you can put in, an interface with an actual method that is really necessary to capture the things you are talking about.

Using Interfaces

Function with Multiple Types of Parameters

Interface expresses similarity, so make the function take as a parameter an interface that expresses the similarity of all desired arguments.

func Area(s Shape) {
  ...
}

Type Assertions

Type Assertions

Mocking

See:

Testify Mocks

Embedded Types

Interface names can be used as embedded types in structs.

TO DEPLETE

Overview

Go has an unique interface system that allows programs to model behavior rather than model types: the behavior is "attached" to types via methods, and, independently, the behavior contract is defined by interfaces. The fact that a type implements an interface is not formally declared via a keyword, like in Java, or otherwise, but is an implicit consequence of a type "having" all the behavior declared by the interface. This is called duck typing. If a type implements an interface by the virtue of duck typing, a value of the type can be stored in a value of that interface type and the compiler ensure the assignments are correct at compile-time.

Is this a good thing? As far as I can tell, I can't say whether a specific type implements an interface, short of browsing all methods in the package, looking for receivers of that specific type. The compiler does that easily, but I don't. This does not help code readability.

A type and its associated pointer type may or may not implement the same interface, depending on how the methods are "associated" with the value and pointers of that type. In order to understand how a type or its corresponding pointer type implements an interface, you need to understand method sets, which will be explained below. The notion of a type implementing an interface is related to method set inclusion. For more details see "When does a type/pointer type implement an interface?" below.

Any used-defined named type (structs, aliased types) can be made to implement interfaces.

The fact that Go detaches the contract from implementation with interfaces allows for polymorphism. Wen a method call is made against an interface value, the equivalent method of the stored user-defined type value it is executed. The user-defined type that implements an interface is often called a concrete type for that interface.

Interfaces in Go tend to be small, exposing only a few functions, or just one function.

Method Sets

A type may have a method set associated with it.

There are two kinds of method sets: interface method sets and user-defined types method sets. In the case of user-defined type method set, there's a distinction between the type method set and the pointer type method set, as it will be shown below.

If a type does not have any of the previously mentioned method sets, it is said to have an empty method set.

In a method set, each method must have a unique non-blank method name.

The language specification defines the method sets here: https://golang.org/ref/spec#Method_sets.

Interface Method Set

An interface method set is a list of method declarations (function name and signature), specified in the interface type declaration. The interface type declaration has the only purpose of defining the method set and giving it a name - the interface name.

The method set only contains method names and signatures, so the interface type does not define how the behavior is implemented, but just the behavior's contract. The interfaces allow us to hide the incidental details of the implementation. The behavior implementation details are contained by user-defined types, via methods.

Also, the method signatures from the interface method set are independent on whether the corresponding methods from the concrete types are declared with value or pointer receivers.

Interface Type

An interface type is a user-defined type whose only purpose is to introduce a method set (the interface method set) and to give it a name.

The interface type declaration starts with the type keyword, to indicated that this is a user-defined type, followed by the interface name and the keyword interface, followed by the interface method set declaration between curly braces. The interface method set declaration consists in a list of method names followed by their signatures. Unlike in the struct's case, we don't define fields.

type MyInterface interface {
 
    <function-name-1><function-signature-1>
    <function-name-2><function-signature-2>
     ...
}

Example:

type A interface {

    m1(i int) int
    m2(s string) string

}

Interface Name Convention

If the interface type contains only one method, the name of the interface starts with name of the method and ends with the er suffix. When multiple methods are declared within an interface type, the name of the interface should relate to its general behavior.

Interface

The method set of an interface type it is said to be the type's interface.

User-Defined Type Method Set

Method Set associated with the Values of a Type

The method set associated with the values of a type consists of all methods declared with a value receiver of that type.

The specification defines the method set of a type as the method set associated with the values of the type.

Method Set associated with the Pointers of a Type

The method set associated with the pointers of a type T consists of both all methods declared with a pointer receiver *T and with a value receiver T.

The method set associated with the pointers of a type always includes the method set associated with the values of the type. This is because given a pointer, we can always infer the value pointed by that address, so the methods associated with the value will naturally "work". The reverse is not true - given a value, not always we can get an address for it, and because we are not able to get an pointer, we cannot assume that the methods associated with the pointer will work. This is an example that demonstrates that we cannot always get an address for a value.

Another way of expressing this is that pointer receiver method are less general than the value receiver methods: value receiver methods can always be used, pointer receiver methods can't always be used.

Also see:

Receivers and Interfaces

When does a Type/Pointer Type Implement an Interface?

Note that notion of a type implementing an interface and its corresponding pointer type implementing the same interface both make sense, and they are subtly different.

According to the language specification, a user-defined type T implements an interface if its method set (all methods declared with a value receiver of type T) is a superset of the interface.

By extrapolation, a pointer type implements an interface when the method set associated with pointers to that type is a superset of the interface. As per User-Defined Type Method Set section, the method set associated with the pointer of a type include implicitly the method set associated with the value of the type.

For more details about value and pointer receivers, see:

Value and Pointer Receivers

For more details about pointer types see:

Pointer Types

Example

The example that follows shows how a type B implements interface A:

//
// The interface A declares an interface method set containing a single method m()
//
type A interface {
    m()
}

//
// At this point, the type B is not yet linked to the interface A in any way. 
// Its method set is empty, so it does not implement interface A, it does not 
// implement any interface.
//
type B struct {
    i int
}

//
// We make B implement interface A by declaring B as a value receiver for m(). 
// This means B's method set includes now m() and it is a superset of A's method 
// set.
//
func (b B) m() {
    // simply reports the value of i
    fmt.Println(b.i)
}

...

//
// B now implements A, so B instances can be assigned to A variables
//
var a A
a = B{1}
a.m()

//
// *B now also implements A, because the method set of the pointer type 
// includes the methods declared agains the value  so *B instances 
// can be assigned to A variables
//
var a2 A
a2 = &B{2}
a2.m()

...

A Variation of the Example

Note that if in the example above we declare

func (b *B) m() {
    ...
}

instead of

func (b B) m() {
    ...
}

then the a = B{1} assignment would fail to compile with:

./main.go:23: cannot use B literal (type B) as type A in assignment:
	B does not implement A (m method has pointer receiver)

This is because the type B does not implement the interface, because m() is not in the type B method set.

However, if we try:

var a A
a = &B{1}
a.m() 

it works in both cases, because the method set associated with the B pointers include both func (b B) m() ... and func (b *B) m() ... so the pointer type B implements the interface.

Passing Interfaces to Functions

Interfaces can be used as arguments to functions. Passing an interface instance insures that the function body can rely on the fact the interface methods are available on the passed instance.

With the example above, we declare a function f() that expects an interface A and we pass a B instance when invoking the function:

...

type A interface {
    m()
}

func (b B) m() {
    ...
}

func f(a A) {
    a.m()
}

...
b := B{1}
f(b)
...

Note that the B instance can be passed by value (as in the example above) or by reference (as in the example below). Both cases work for reasons explained in the Method Set associated with the Pointers of a Type section:

...
b := B{1}
f(&b)
...

or (same thing)

...
bPtr := new(B)
f(bPtr)
...

Interfaces as Fields

Interfaces can be used as fields in structs.

Implementation Details

An interface variable is a two-word data structure.

The first word contains a pointer to an internal table called iTable, which contains type information about the stored value: the concrete type of the value that has been stored and a list of methods associated with the value. The second word is a reference to the stored value.

The combination of type information and pointer binds the relationship between the two values.

DEPLETE: Go Concepts - The Type System