Interfaces principales de la biblioteca estándar
fmt.Stringer, io.Reader, io.Writer
Interfaces principales de la biblioteca estándar es una lección gratuita de Go Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Go Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Go Academy incluye 4 lecciones en total.
fmt.Stringer
fmt.Stringer tiene un método: String() string. Impleméntelo para controlar cómo aparece su tipo con fmt.Println y %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
}Interfaz error
La interfaz integrada error tiene un método: Error() string. Cualquier tipo que lo implemente puede utilizarse como error:
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 tiene un método: Read(p []byte) (n int, err error). Los archivos, los cuerpos de respuestas HTTP, las cadenas y los búferes lo implementan:
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 tiene un método: Write(p []byte) (n int, err error). Lo utilizan fmt.Fprintf, los sistemas de registro, los escritores de respuestas 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
La biblioteca estándar combina interfaces pequeñas para formar otras más grandes:
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 requiere Len() int, Less(i, j int) bool y 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 tiene un método: ServeHTTP(ResponseWriter, *Request). Toda la pila HTTP de Go se basa en esta única interfaz:
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 la representación con sintaxis de Go de su tipo, %#v:
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) y UnmarshalText([]byte) error para crear una codificación de texto personalizada (cadenas 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
}Combinar interfaces estándar
Combine interfaces estándar con io.TeeReader, io.MultiWriter, etc. para crear canalizaciones potentes sin escribir tipos nuevos:
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
}Comprobación rápida
¿Qué interfaz debe implementar un tipo para poder utilizarse como error en Go?
Repaso
Interfaces principales de la biblioteca estándar:
fmt.Stringer: representación personalizada para impresiónerror: valores de errorio.Reader/io.Writer: E/S mediante streamssort.Interface: ordenación personalizadahttp.Handler: gestión de solicitudes HTTP
Propuesta de práctica
Implemente sort.Interface en un []Person (donde Person tiene los campos Name y Age) para ordenar por edad de forma descendente. Imprima la lista ordenada.
Preguntas frecuentes
¿La lección «Interfaces principales de la biblioteca estándar» es gratis?
Sí — el texto completo de «Interfaces principales de la biblioteca estándar» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Go Academy, actualiza a CoddyKit PRO. El curso de Go Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Interfaces principales de la biblioteca estándar»?
fmt.Stringer, io.Reader, io.Writer Practicas Go Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Go Academy?
No se requiere experiencia previa. Go Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «Interfaces principales de la biblioteca estándar»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Go Academy?
Sí. Cada lección de Go Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Definición e implementación de interfaces
- Interfaces principales de la biblioteca estándar
- Aserciones de tipo y switches de tipo
- Composición de interfaces y buenas prácticas