0Pricing
Go Academy · Aula

Interfaces essenciais da biblioteca padrão

fmt.Stringer, io.Reader e io.Writer

Interfaces essenciais da biblioteca padrão é uma aula grátis de Go Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Go Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Go Academy inclui 4 aulas no total.

fmt.Stringer

fmt.Stringer tem um método: String() string. Implemente-o para controlar como seu tipo aparece com 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
}

Interface error

A interface integrada error tem um método: Error() string. Qualquer tipo que a implemente pode ser usado como um erro:

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 tem um método: Read(p []byte) (n int, err error). Arquivos, corpos de respostas HTTP, strings e buffers implementam essa interface:

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 tem um método: Write(p []byte) (n int, err error). É usado por fmt.Fprintf, registros, gravadores de respostas HTTP etc.:

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

A biblioteca padrão combina interfaces pequenas em interfaces maiores:

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 exige 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 tem um método: ServeHTTP(ResponseWriter, *Request). Tudo na pilha HTTP de Go é construído sobre essa única interface:

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

Implemente GoString() string para controlar a representação %#v (sintaxe de Go) do seu 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

Implemente MarshalText() ([]byte, error) e UnmarshalText([]byte) error para criar uma codificação de texto personalizada (strings JSON, YAML etc.):

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
}

Compondo Interfaces Padrão

Combine interfaces padrão com io.TeeReader, io.MultiWriter etc. para criar fluxos poderosos sem escrever tipos novos:

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ção Rápida

Qual interface um tipo precisa implementar para ser usado como um erro em Go?

Recapitulação

Principais interfaces da biblioteca padrão:

  • fmt.Stringer — representação personalizada para impressão
  • error — valores de erro
  • io.Reader / io.Writer — E/S em fluxo
  • sort.Interface — ordenação personalizada
  • http.Handler — tratamento de requisições HTTP

Proposta de Prática

Implemente sort.Interface em uma []Person (em que Person tem os campos Name e Age) para ordenar por idade decrescente. Imprima a lista ordenada.

Perguntas Frequentes

A aula “Interfaces essenciais da biblioteca padrão” é grátis?

Sim — o texto completo de “Interfaces essenciais da biblioteca padrão” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Go Academy, atualize para CoddyKit PRO. O curso de Go Academy inclui 4 aulas no total.

O que vou aprender em “Interfaces essenciais da biblioteca padrão”?

fmt.Stringer, io.Reader e io.Writer Você pratica Go Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Go Academy?

Nenhuma experiência prévia é necessária. Go Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “Interfaces essenciais da biblioteca padrão”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Go Academy?

Sim. Cada aula de Go Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Definindo e implementando interfaces
  2. Interfaces essenciais da biblioteca padrão
  3. Asserções de tipo e switches de tipo
  4. Composição de interfaces e boas práticas
← Voltar para Go Academy