Interfaces in Go
Swipe um das Menü anzuzeigen
You will explore interfaces in Go. You will learn how to define interfaces, how Go's implicit implementation model works, and how interface values behave at runtime.
Defining Interfaces in Go
In Go, an interface is a type that specifies a set of method signatures. Any type that implements those methods satisfies the interface automatically—there is no need for explicit declaration. This enables you to write flexible and reusable code.
To define an interface, use the type keyword followed by the interface name and the interface keyword. Inside the curly braces, list the method signatures required by the interface.
Here is a simple example:
type Greeter interface {
Greet() string
}
This code declares a Greeter interface that requires any type to have a Greet method returning a string. Any type with a matching Greet method will satisfy the Greeter interface.
main.go
1234567891011121314151617181920212223242526package main import ( "fmt" ) // Speaker defines an interface with a single method type Speaker interface { Speak() string } // Dog struct implicitly implements the Speaker interface type Dog struct { Name string } // Speak method matches the Speaker interface func (d Dog) Speak() string { return "Woof! My name is " + d.Name } func main() { var s Speaker s = Dog{Name: "Buddy"} fmt.Println(s.Speak()) }
Danke für Ihr Feedback!
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen