An interface type is defined as a set of method signatures.
A value of interface type can hold any value that implements those methods. 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.
Interface values can be thought of as a tuple of (a value and a concrete type)
Calling a method on a nil interface is a run-time error because there is no type inside the interface tuple to indicate which concrete method to call.
The interface type that specifies zero methods is known as the empty interface. An empty interface may hold values of any type. Empty interfaces are used by code that handles values of unknown type.
type Abser interface { Abs() float64} type Vertex struct { X,Y float64} //This method means type *Vertex implements the interface Abser func (v *Vertex) Abs() float64{ return math.Sqrt(v.X*v.X + v.Y*v.Y) } func main() { var a Abser v := Vertex{3,4} a = &v
fmt.Printf("(%v, %T)\n", a, a)//(&{3 4}, *main.Vertex) fmt.Println(a.Abs()) }
No comments:
Post a Comment