Série: Go
go
75 lignes
· Mis à jour 2026-04-18
main.go
Go/part1-language/examples/07_interfaces/main.go
// Demonstrates interfaces, satisfaction, type switches, custom errors.
package main
import (
"errors"
"fmt"
)
type Speaker interface {
Speak() string
}
type Dog struct{ Name string }
func (d Dog) Speak() string { return d.Name + ": woof" }
type Cat struct{ Name string }
func (c Cat) Speak() string { return c.Name + ": meow" }
type Money struct{ Cents int }
func (m Money) String() string {
return fmt.Sprintf("$%d.%02d", m.Cents/100, m.Cents%100)
}
type ValidationError struct {
Field, Reason string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation: %s: %s", e.Field, e.Reason)
}
func validate(name string) error {
if name == "" {
return &ValidationError{Field: "name", Reason: "required"}
}
return nil
}
func describe(x any) string {
switch v := x.(type) {
case nil:
return "nil"
case int:
return fmt.Sprintf("int %d", v)
case string:
return fmt.Sprintf("string %q", v)
case fmt.Stringer:
return "stringer: " + v.String()
default:
return fmt.Sprintf("other %T", v)
}
}
func main() {
animals := []Speaker{Dog{"Rex"}, Cat{"Mia"}}
for _, a := range animals {
fmt.Println(a.Speak())
}
fmt.Println(describe(42))
fmt.Println(describe("go"))
fmt.Println(describe(Money{Cents: 1099}))
fmt.Println(describe(3.14))
fmt.Println(describe(nil))
if err := validate(""); err != nil {
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Println("got validation err on field:", ve.Field)
}
}
}
Articles liés
Go
go
Mis à jour 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/hashpw/main.go).
Lire l'article →
Go
go
Mis à jour 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/server/main.go).
Lire l'article →
Go
go
Mis à jour 2026-04-18
docs.go
docs.go — go source code from the Go learning materials (Go/Baasid/docs/docs.go).
Lire l'article →
Go
go
Mis à jour 2026-04-18
jwt.go
jwt.go — go source code from the Go learning materials (Go/Baasid/internal/auth/jwt.go).
Lire l'article →
Go
go
Mis à jour 2026-04-18
password.go
password.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password.go).
Lire l'article →
Go
go
Mis à jour 2026-04-18
password_test.go
password_test.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password_test.go).
Lire l'article →