课程: Hands-On Introduction: Go

Defining and implementing interfaces - Go教程

课程: Hands-On Introduction: Go

Defining and implementing interfaces

- [Instructor] One of Go's differentiating language features is how it treats interfaces. The usual requirement that types specify what interface to implement is not present in Go, making it one of its most powerful concepts to grasp early in your learning journey. Let's dive in. We'll start by defining an interface type to work with. We'll declare humanoid type with interface as its underlying type. Interfaces specify a set of methods that must be implemented. So let's add a couple to our humanoid type. We'll define speak and walk as the two methods. We'll now define two additional types. Starting with person. Remember, you don't need to specify that person implements humanoid anywhere in the code. Simply implementing the interface's methods will do the trick. Let's do that now. Let's now define a dog but we'll only implement the walk method on it. Before we can use our types, let's uncommon the do humanoid things function now that we have the humanoid type defined. Note how the function makes use of the speak and what methods that are expected of the argument passed in. We'll now initialize these two types in our main and attempt to pass them to our do humanoid function. Let's now run the program. And voila. We have James speaking and James walking. As expected, our person value satisfies our humanoid interface requirement. Now let's attempt to do the same thing with our value of type dog. Let's run our program. Our dog value failed to meet the requirement even though it partially met them. A key takeaway here is that types are required to implement all of the methods of an interface. Types are allowed to implement as many interfaces as they wish. Let's take the standard library Stringer interface for example. Implementing the stringer interface lets us override the default way Go formats our values when we print them out. When we print out our person value, the default output may not be what we want. We'll clear the console and run the program again. This being our default output for person. Let's change this by making sure our person type implements the Stringer interface. Now let's run the program again and compare the outputs. And voila, we're able to override the default output by simply implementing the Stringer interface. Our person type implicitly implements both the locally defined humanoid interface as well as the standard library defined Stringer interface. Let's now talk about the empty interface next.

内容