0Pricing
Go Academy · Lezione

Interfacce fondamentali della libreria standard

fmt.Stringer, io.Reader, io.Writer

Interfacce fondamentali della libreria standard è una lezione Go Academy gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Go Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Go Academy include 4 lezioni in totale.

fmt.Stringer

fmt.Stringer ha un metodo: String() string. Lo implementi per controllare come viene visualizzato il tipo con fmt.Println e %v:

package main
import "fmt"

type Color int
const (Red Color = iota; Green; Blue)
func (c Color) String() string {
    return []string{"Red","Green","Blue"}[c]
}

func main() {
    fmt.Println(Red, Green, Blue) // Red Green Blue
}

Interfaccia error

L'interfaccia incorporata error ha un metodo: Error() string. Qualsiasi tipo che lo implementa può essere usato come errore:

package main
import "fmt"

type ValidationError struct{ Field, Msg string }
func (e *ValidationError) Error() string {
    return e.Field + ": " + e.Msg
}

func validate(age int) error {
    if age < 0 { return &ValidationError{"age", "must be non-negative"} }
    return nil
}

func main() {
    fmt.Println(validate(-1))
}

io.Reader

io.Reader ha un metodo: Read(p []byte) (n int, err error). File, corpi delle risposte HTTP, stringhe e buffer lo implementano:

package main
import ("fmt"; "strings")

func countBytes(r interface{ Read([]byte)(int,error) }) int {
    buf := make([]byte, 512)
    total := 0
    for {
        n, err := r.Read(buf)
        total += n
        if err != nil { break }
    }
    return total
}

func main() {
    r := strings.NewReader("hello world")
    fmt.Println(countBytes(r)) // 11
}

io.Writer

io.Writer ha un metodo: Write(p []byte) (n int, err error). Viene usato da fmt.Fprintf, dai logger, dai writer delle risposte HTTP e così via:

package main
import ("bytes"; "fmt")

func main() {
    var buf bytes.Buffer
    fmt.Fprintf(&buf, "Hello, %s!", "Go")
    fmt.Println(buf.String()) // Hello, Go!
}

io.ReadWriter e io.Closer

La libreria standard combina interfacce piccole in interfacce più grandi:

package main
import "io"

// io.ReadWriter = io.Reader + io.Writer
// io.ReadCloser = io.Reader + io.Closer
// io.ReadWriteCloser = all three

func process(rw io.ReadWriter) {
    buf := make([]byte, 8)
    rw.Read(buf)
    rw.Write(buf)
}

func main() { _ = process }

sort.Interface

sort.Interface richiede Len() int, Less(i, j int) bool e Swap(i, j int):

package main
import ("fmt"; "sort")

type ByLength []string
func (b ByLength) Len() int           { return len(b) }
func (b ByLength) Less(i, j int) bool { return len(b[i]) < len(b[j]) }
func (b ByLength) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }

func main() {
    fruits := ByLength{"banana","apple","kiwi"}
    sort.Sort(fruits)
    fmt.Println([]string(fruits)) // [kiwi apple banana]
}

http.Handler

http.Handler ha un metodo: ServeHTTP(ResponseWriter, *Request). L'intero stack HTTP di Go si basa su questa singola interfaccia:

package main
import ("fmt"; "net/http")

type Hello struct{}
func (h Hello) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, World!")
}

func main() {
    http.ListenAndServe(":8080", Hello{})
}

fmt.GoStringer

Implementi GoString() string per controllare la rappresentazione %#v (sintassi Go) del tipo:

package main
import "fmt"

type Version struct{ Major, Minor int }
func (v Version) GoString() string {
    return fmt.Sprintf("Version{%d, %d}", v.Major, v.Minor)
}

func main() {
    fmt.Printf("%#v\n", Version{1, 18}) // Version{1, 18}
}

encoding.TextMarshaler

Implementi MarshalText() ([]byte, error) e UnmarshalText([]byte) error per una codifica testuale personalizzata (stringhe JSON, YAML e così via):

package main
import "fmt"

type Status int
const (Active Status = iota; Inactive)
func (s Status) MarshalText() ([]byte, error) {
    if s == Active { return []byte("active"), nil }
    return []byte("inactive"), nil
}

func main() {
    s := Active
    b, _ := s.MarshalText()
    fmt.Println(string(b)) // active
}

Comporre interfacce standard

Combini interfacce standard con io.TeeReader, io.MultiWriter e così via per creare pipeline potenti senza scrivere nuovi tipi:

package main
import ("bytes"; "fmt"; "io"; "strings")

func main() {
    r := strings.NewReader("hello")
    var buf bytes.Buffer
    tee := io.TeeReader(r, &buf)
    io.ReadAll(tee)
    fmt.Println(buf.String()) // hello
}

Verifica rapida

Quale interfaccia deve implementare un tipo per poter essere usato come errore in Go?

Riepilogo

Principali interfacce della libreria standard:

  • fmt.Stringer — rappresentazione personalizzata per la stampa
  • error — valori di errore
  • io.Reader / io.Writer — I/O a flusso
  • sort.Interface — ordinamento personalizzato
  • http.Handler — gestione delle richieste HTTP

Esercizio

Implementi sort.Interface su una []Person (dove Person ha i campi Name e Age) per ordinare in base all'età decrescente. Stampi l'elenco ordinato.

Domande Frequenti

La lezione «Interfacce fondamentali della libreria standard» è gratuita?

Sì — il testo completo di «Interfacce fondamentali della libreria standard» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Go Academy, passa a CoddyKit PRO. Il corso Go Academy include 4 lezioni in totale.

Cosa imparerò in «Interfacce fondamentali della libreria standard»?

fmt.Stringer, io.Reader, io.Writer Eserciti Go Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Go Academy?

Non è richiesta alcuna esperienza precedente. Go Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.

Quanto tempo richiede la lezione «Interfacce fondamentali della libreria standard»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Go Academy?

Sì. Ogni lezione Go Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Definire e implementare le interfacce
  2. Interfacce fondamentali della libreria standard
  3. Asserzioni di tipo e switch sul tipo
  4. Composizione delle interfacce e buone pratiche
← Torna a Go Academy