首页 > 其他分享 >【转】io.Reader in depth

【转】io.Reader in depth

时间:2022-11-12 14:35:37浏览次数:73  
标签:Reverse err bytes depth io Reader string

func Reverse(s string) (string, error)
func Reverse(r io.Reader) io.Reader

 

----------------------------

 

io.Reader in depth

This article aims to convince you to use io.Reader in your own code wherever you can.

Let’s have a look at io.Reader:

type Reader interface {
Read(p []byte) (n int, err error)
}

Examples of readers

There are many kinds of Reader types available in the standard library, and you’ve almost certainly used at least one of them.

var r io.Reader
var err error
r, err = os.Open("file.txt")
var r io.Reader
r = strings.NewReader("Read will return these bytes")
var r io.Reader
r = request.Body
var r io.Reader
var buf bytes.Buffer
r = &buf

Using readers

Now we have a few Reader types — let’s explore ways in which they can be used.

p := make([]byte, 256)
n, err := r.Read(p)
b, err := ioutil.ReadAll(r)
n, err := io.Copy(w, r)
err := json.NewDecoder(r).Decode(v)
r = gzip.NewReader(r)

Take io.Reader when you can

If you’re designing a package or utility (even if it’s an internal thing that nobody will ever see) rather than taking in strings or []byte slices, consider taking in an io.Reader if you can for data sources. Because suddenly, your code will work with every type that implements io.Reader.

func Reverse(s string) (string, error)
func Reverse(r io.Reader) io.Reader
r = Reverse(strings.NewReader("Make me backwards"))
f, err := os.Open("file.txt")
if err != nil {
log.Fatalln(err)
}
r = Reverse(f)
func handle(w http.ResponseWriter, r *http.Request) {  rev := Reverse(r.Body)  // etc...
}

标签:Reverse,err,bytes,depth,io,Reader,string
From: https://www.cnblogs.com/oxspirt/p/16883682.html

相关文章