interfaces define a set of methods. Any type that implements these methods satisfies the interface.
Example of an Interface Implementation:
Output:
interfaces define a set of methods. Any type that implements these methods satisfies the interface.
Example of an Interface Implementation:
package main
==========================
import "fmt"
// Interface definition
type Printable interface {
PrintInfo() string
}
==========================
// Struct that implements the interface
type User struct {
Name string
Email string
}
==========================
// Implement the interface
func (u User) PrintInfo() string {
return fmt.Sprintf("Name: %s, Email: %s", u.Name, u.Email)
}
==========================
func main() {
user := User{Name: "Le Giang", Email: "le.giang@example.com"}
var p Printable = user // User satisfies the Printable interface
fmt.Println(p.PrintInfo())
}
Output:
Name: Le Giang, Email: le.giang@example.com
No comments:
Post a Comment