1. Introduction
It is a Go language standard library that provides a structure type, which is very useful in discarding unnecessary data scenarios.
This article we willStarting from the basic definition of types, it describes its basic usage and implementation principles, and then briefly describes them.
The usage scenarios are based on this
Introduction to the type.
2. Introduction
2.1 Basic definition
It is a Go language provided by
Writer
,thisWriter
It's special, it won't do anything. It will write the dataDiscard immediately, no processing will be done. Its definition is as follows:
type discard struct{} func (discard) Write(p []byte) (int, error) {} func (discard) WriteString(s string) (int, error) {} func (discard) ReadFrom(r Reader) (n int64, err error) {}
discard
The structure type does not define any fields, and it also providesWrite
,ReadFrom
andWriteString
method,Write
Methods andWriteString
The method receives byte slices and strings respectively, and then returns the number of bytes written.
It also achievedInterface, this is for use
When function, copy data from source to
When avoiding unnecessary operations.
From abovediscard
The definition of can seem that it is not a public type of structure type, so we cannot create structure instances. In fact, Go provides aWe use the predefined constants of instances directly without creating an instance by ourselves. The definition is as follows:
var Discard Writer = discard{}
2.2 Instructions for use
The following is an example of discarding data that is no longer needed in a network connection.The code examples are as follows:
package main import ( "fmt" "io" "net" "os" ) func discardData(conn , bytesToDiscard int64) error { _, err := (, conn, bytesToDiscard) return err } func main() { conn, err := ("tcp", ":80") if err != nil { ("Connection Error:", err) return } defer () bytesToDiscard := int64(1024) // Number of bytes to be discarded err = discardData(conn, bytesToDiscard) if err != nil { ("Dropping data error:", err) return } ("The data has been successfully discarded.") }
In the example above, we set up a network connection and then the first 1024 bytes of data in the connection are not needed. At this time, we passFunctions transfer data from
conn
Copy toAmong them, based on
The feature of discarding data is successfully discarded, and the first 1024 bytes of the connection is not required, without the need for operations such as custom buffers, which is simple and efficient.
3. Implementation principle
The purpose is to provide a satisfying situation in some scenarios
An instance of the interface, but the user does not care about the data write operation. It can be used as a black hole-like write target, silently discarding all data written to it. so
The implementation is relatively simple, and it is enough to not process the input data. Let’s take a look at the specific implementation below.
First of allThe definition of the structure does not define any fields, because no write operation is required:
type discard struct{}
And forWrite
andWriteString
Method, which directly returns the length of the passed parameter, to thisWriter
The written data will not be written to other places, but will be discarded directly:
func (discard) Write(p []byte) (int, error) { return len(p), nil } func (discard) WriteString(s string) (int, error) { return len(s), nil }
at the same timediscard
It has also been achievedThe interface has been implemented
ReadFrom
The method is also very simple to implement, fromblackHolePool
Get byte slices in the buffer pool, and then continuously read the data. After the reading is completed, put the byte slices in the buffer pool again:
// There is a byte slice buffer poolvar blackHolePool = { New: func() any { b := make([]byte, 8192) return &b }, } func (discard) ReadFrom(r Reader) (n int64, err error) { // Take a byte slice from the buffer pool bufp := ().(*[]byte) readSize := 0 for { // Continuously reading data, bufp is just an intermediary for reading data, and the data read is meaningless readSize, err = (*bufp) n += int64(readSize) if err != nil { // Replace byte slice into blackHolePool (bufp) if err == EOF { return n, nil } return } } }
existIn the function, it will be called
discard
In-comeReadFrom
Method, canWriter
All data in it is read and discarded.
4. Use scenarios
Provide us with a
An instance of an interface, but it does not really write data, is very useful in some scenarios.
Sometimes, we may need an implementationInstance of the interface, but we don't care about data writing
Writer
The result is not concerned with whether the data has been written where it is written.This provides us with a convenient solution. at the same time
It can be written as a black hole to the target, and can silently discard data without actual processing and storage.
So if we want to discard certain data, or we need oneAn instance of the interface, but does not need attention to the write result, then use it
It is very suitable.
5. Summary
Functions are implemented in the Go language standard library
Writer
The structure type of the interface can quietly realize data discarding. Let's start withStarting from the basic definition of the type, then use a simple example to show how to use it
Type implementations discarding of unnecessary data.
Then we talk about itThe implementation principle of type is actually to not perform any operations on the written data. In use scenarios, we want to discard certain data, or we need one
An instance of the interface, but does not need attention to the write result, then use it
It is very suitable.
Based on this, theI hope the introduction of the type will be helpful to you.
The above is a detailed explanation of the discard type in the Go language io package. For more information about the discard type of the Go language io package, please follow my other related articles!