From aef4e1c3492908425d4cefd78ae8dd8a765988b9 Mon Sep 17 00:00:00 2001
From: Andrew Gerrand
+A Go type satisfies an interface by implementing the methods of that interface, +nothing more. This property allows interfaces to be defined and used without +having to modify existing code. It enables a kind of "duck typing" that +promotes separation of concerns and improves code re-use, and makes it easier +to build on patterns that emerge as the code develops. +The semantics of interfaces is one of the main reasons for Go's nimble, +lightweight feel. +
+ ++See the question on type inheritance for more detail. +
+ +
+You can ask the compiler to check that the type T
implements the
+interface I
by attempting an assignment:
+
+type T struct{} +var _ I = T{} ++ +
+If T
doesn't implement I
, the mistake will be caught
+at compile time.
+
+If you wish the users of an interface to explicitly declare that they implement +it, you can add a method with a descriptive name to the interface's method set. +For example: +
+ ++type Fooer interface { + Foo() + ImplementsFooer() +} ++ +
+A type must then implement the ImplementsFooer
method to be a
+Fooer
, clearly documenting the fact.
+
+type Bar struct{} +func (b Bar) ImplementsFooer() {} +func (b Bar) Foo() {} ++ +
+Most code doesn't make use of such constraints, since they limit the utility of +the interface idea. Sometimes, though, they're necessary to resolve ambiguities +among similar interfaces. +
+