36 Introduction
36 Introduction
This lesson gives an introduction to interfaces in Go using an example, also explains how to de ne a new type that
would implement the same interface.
• De nition
• Example
• De ning a New Type
De nition #
An interface type is defined by a set of methods. A value of interface type can
hold any value that implements those methods. Interfaces increase the
flexibility as well as the scalability of the code. Hence, it can be used to
achieve polymorphism in Golang. Interface does not require a particular type,
specifying that only some behavior is needed, which is defined by a set of
methods.
Example #
Here is a refactored version of our earlier example. This time we made the
greeting feature more generic by defining a function called Greet which takes
a param of interface type Namer . Namer is a new interface we defined which
only defines one method: Name() . So Greet() will accept as param any value
which has a Name() method defined.
Environment Variables
Key: Value:
GOPATH /go
package main
import (
"fmt"
)
func main() {
u := &User{"Matt", "Aimonetti"}
fmt.Println(Greet(u))
}
Environment Variables
Key: Value:
GOPATH /go
package main
import (
"fmt"
)
func (u *User) Name() string { //Name method used for type User
return fmt.Sprintf("%s %s", u.FirstName, u.LastName)
}
type Customer struct {
Id int
FullName string
}
func (c *Customer) Name() string { //Name method used for type Customer
return c.FullName
}
func main() {
u := &User{"Matt", "Aimonetti"}
fmt.Println(Greet(u))
c := &Customer{42, "Francesc"}
fmt.Println(Greet(c))
}