Interfaces
Advanced
Struct having extra functions than interface
In Go, if a struct implements more methods than defined in an interface, you can still call the extra methods, but you cannot call them directly on a variable of the interface type without type assertion or type conversion. Here’s an example to illustrate this:
Example
Let’s define an interface Animal and a struct Dog that implements Animal and has an extra method Bark.
package main
import (
"fmt"
)
// Animal interface with one method
type Animal interface {
Speak() string
}
// Dog struct implementing Animal interface
type Dog struct {
Name string
}
// Speak method required by the Animal interface
func (d Dog) Speak() string {
return "Woof!"
}
// Bark is an extra method not defined in the Animal interface
func (d Dog) Bark() string {
return fmt.Sprintf("%s is barking!", d.Name)
}
func main() {
var a Animal
d := Dog{Name: "Buddy"}
a = d
// Call the Speak method from the Animal interface
fmt.Println(a.Speak())
// Attempting to call Bark method directly on interface variable 'a' will result in an error
// fmt.Println(a.Bark()) // This won't compile
// Type assertion to access the extra method
if dog, ok := a.(Dog); ok {
fmt.Println(dog.Bark())
} else {
fmt.Println("Type assertion failed")
}
// Another way to access the extra method by converting interface back to struct type
dog := a.(Dog)
fmt.Println(dog.Bark())
}Explanation
- Interface Definition: The
Animalinterface has a single methodSpeak. - Struct Definition: The
Dogstruct implements theAnimalinterface by providing theSpeakmethod. It also has an extra methodBark. - Assignment: A
Doginstance is assigned to anAnimalinterface variable. SinceDogimplementsAnimal, this assignment is valid. - Calling Methods:
- You can call the
Speakmethod directly on the interface variablea. - You cannot call the
Barkmethod directly on the interface variableabecauseAnimaldoes not have aBarkmethod.
- You can call the
- Type Assertion:
- Using type assertion, you can access the underlying
Dogtype and call theBarkmethod. - The syntax
a.(Dog)converts the interface variable back to theDogtype.
- Using type assertion, you can access the underlying
- Type Conversion:
- You can also use a type conversion directly to call the
Barkmethod, but make sure that the conversion is safe and the type assertion succeeds.
- You can also use a type conversion directly to call the
Summary
If a struct implements more methods than defined in an interface, you can call the extra methods by asserting the interface back to the struct type. Directly calling the extra methods on the interface variable without type assertion is not possible.