in go, interfaces are fundamental to promoting polymorphism and abstraction. They act as contracts that specify a set of methods that a type should implement, allowing different types to be treated uniformly and flexibly.
In Go, an interface is a type that defines a set of methods without implementing them. It specifies only the signatures of the methods that a type must have to satisfy the interface. This allows different types to be treated uniformly as long as they implement the methods defined by the interface. Interfaces promote polymorphism and abstraction, facilitating the creation of flexible and reusable code.
The io.writer interface is one of the most used in GO. It defines the write method, which receives a blyte from Bytes ([] byte) and returns an integer (int) and an error (error). Several types implement this interface, including OS.File, Bytes.buffer and net.conn. This allows different types of writing destinations to be treated uniformly and flexibly.
// Writer é a interface que encapsula a operação básica de escrita. type Writer interface { Write(p []byte) (n int, err error) }
Any type that implements the write method with the correct subscription will be considered an io.writer.
package main import ( "fmt" "os" "io" ) func main() { var w io.Writer = os.Stdout // w é do tipo io.Writer n, err := w.Write([]byte("Hello, World!")) if err != nil { fmt.Println("Erro:", err) } fmt.Printf("\bBytes escritos: %b", n) }
/tmp ➜ go run example_io_writer.go Hello, World! Bytes escritos: 1101
The io.writer interface is one of the most common interfaces in GO. It is used to abstract data writing operation, allowing different types of writing destinations to be treated uniformly. This facilitates the reuse of code, the creation of generic methods and the writing of tests. In addition, the io.writer interface promotes polymorphism, allowing different types that implement the interface are used interchangeably. It is widely implemented in several standard GO language packages, such as the, bytes, net, among others, demonstrating its versatility and importance in the GO ecosystem.
https://pkg.go.dev/io#writer
https://pkg.go.dev/[email protected]#file.writal*
https://pkg.go.dev/log/slog/internal/buffer#buffer.write*&&&]
https://pkg.go.dev/[email protected]#Conn*&&&]
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3