interface
An interface type is defined as a set of method signatures.
A value of interface type can hold any value that implements those methods.
Interfaces in Go provide a way to specify the behavior of an object: if something can do this, then it can be used here. We’ve seen a couple of simple examples already; custom printers can be implemented by a String
method while Fprintf
can generate output to anything with a Write
method. Interfaces with only one or two methods are common in Go code, and are usually given a name derived from the method, such as io.Writer
for something that implements Write
.
Note: There is an error in the example code on line 22 (a = v
). Vertex
(the value type) doesn’t implement Abser
because the Abs
method is defined only on *Vertex
(the pointer type).
package main
import (
"fmt"
"math"
)
type Abser interface {
Abs() float64
}
func main() {
var a Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}
a = f // a MyFloat implements Abser
a = &v // a *Vertex implements Abser
// In the following line, v is a Vertex (not *Vertex)
// and does NOT implement Abser.
a = v
fmt.Println(a.Abs())
}
type MyFloat float64
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
A type can implement multiple interfaces. For instance, a collection can be sorted by the routines in package sort
if it implements sort.Interface
, which contains Len()
, Less(i, j int) bool
, and Swap(i, j int)
, and it could also have a custom formatter. In this contrived example Sequence
satisfies both.
type Sequence []int
// Methods required by sort.Interface.
func (s Sequence) Len() int {
return len(s)
}
func (s Sequence) Less(i, j int) bool {
return s[i] < s[j]
}
func (s Sequence) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// Copy returns a copy of the Sequence.
func (s Sequence) Copy() Sequence {
copy := make(Sequence, 0, len(s))
return append(copy, s...)
}
// Method for printing - sorts the elements before printing.
func (s Sequence) String() string {
s = s.Copy() // Make a copy; don't overwrite argument.
sort.Sort(s)
str := "["
for i, elem := range s { // Loop is O(N²); will fix that in next example.
if i > 0 {
str += " "
}
str += fmt.Sprint(elem)
}
return str + "]"
}
Analysis 1 - Interfaces are implemented implicitly
A type implements an interface by implementing its methods. There is no explicit declaration of intent, no “implements” keyword.
Implicit interfaces decouple the definition of an interface from its implementation, which could then appear in any package without prearrangement.
package main
import "fmt"
type I interface {
M()
}
type T struct {
S string
}
// This method means type T implements the interface I,
// but we don't need to explicitly declare that it does so.
func (t T) M() {
fmt.Println(t.S)
}
func main() {
var i I = T{"hello"}
i.M()
}
interface{}
Type(Empty Interface)
我们可以使用类型断言(type assertion),以将一个类型为 interface{}
的变量,转换为基本数据类型或者复杂数据类型:
import "fmt"
func main() {
var v interface{}
v = "aaa"
if v, ok := v.(string); ok {
fmt.Println(v)
}
fmt.Println(v)
}
Analysis 1
One important category of type is interface types, which represent fixed sets of methods. An interface variable can store any concrete (non-interface) value as long as that value implements the interface’s methods. A well-known pair of examples is io.Reader
and io.Writer
, the types Reader
and Writer
from the io package:
// Reader is the interface that wraps the basic Read method.
type Reader interface {
Read(p []byte) (n int, err error)
}
// Writer is the interface that wraps the basic Write method.
type Writer interface {
Write(p []byte) (n int, err error)
}
Any type that implements a Read
(or Write
) method with this signature is said to implement io.Reader
(or io.Writer
). For the purposes of this discussion, that means that a variable of type io.Reader
can hold any value whose type has a Read
method:
var r io.Reader
r = os.Stdin
r = bufio.NewReader(r)
r = new(bytes.Buffer)
// and so on
It’s important to be clear that whatever concrete value r
may hold, r
’s type is always io.Reader
: Go is statically typed and the static type of r
is io.Reader
.
An extremely important example of an interface type is the empty interface:
interface{}
It represents the empty set of methods and is satisfied by any value at all, since any value has zero or more methods.
Some people say that Go’s interfaces are dynamically typed, but that is misleading. They are statically typed: a variable of interface type always has the same static type, and even though at run time the value stored in the interface variable may change type, that value will always satisfy the interface.
Analysis 2 - The representation of an interface
Russ Cox has written a detailed blog post about the representation of interface values in Go. It’s not necessary to repeat the full story here, but a simplified summary is in order.
A variable of interface type stores a pair: the concrete value assigned to the variable, and that value’s type descriptor. To be more precise, the value is the underlying concrete data item that implements the interface and the type describes the full type of that item. For instance, after
var r io.Reader
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return nil, err
}
r = tty
r
contains, schematically, the (value, type) pair, (tty
, *os.File
). Notice that the type *os.File
implements methods other than Read
; even though the interface value provides access only to the Read
method, the value inside carries all the type information about that value. That’s why we can do things like this:
var w io.Writer
w = r.(io.Writer)
The expression in this assignment is a type assertion; what it asserts is that the item inside r
also implements io.Writer
, and so we can assign it to w
. After the assignment, w
will contain the pair (tty
, *os.File
). That’s the same pair as was held in r
. The static type of the interface determines what methods may be invoked with an interface variable, even though the concrete value inside may have a larger set of methods.
Continuing, we can do this:
var empty interface{}
empty = w
and our empty interface value empty
will again contain that same pair, (tty
, *os.File
). That’s handy: an empty interface can hold any value and contains all the information we could ever need about that value.
(We don’t need a type assertion here because it’s known statically that w
satisfies the empty interface. In the example where we moved a value from a Reader
to a Writer
, we needed to be explicit and use a type assertion because Writer
’s methods are not a subset of Reader
’s.)
One important detail is that the pair inside an interface always has the form (value, concrete type) and cannot have the form (value, interface type). Interfaces do not hold interface values.
Reference
- https://golang.org/ref/spec
- https://golang.org/doc/effective_go#interfaces
- https://go.dev/blog/laws-of-reflection
- https://research.swtch.com/interfaces