A Tour of Go部分练习

文章目录

    • Reader 练习

Reader 练习

https://golang.google.cn/tour/methods/22

实现io.Reader接口

package main

import (
	//"golang.org/x/tour/reader"
	"fmt"
	"strings"
)

type MyReader struct{}

// TODO: Add a Read([]byte) (int, error) method to MyReader.

type ErrEmptyBuffer []byte

func (b ErrEmptyBuffer) Error() string {
	return fmt.Sprintf("cannot read empty buffer")
}

func (mr MyReader) Read (b []byte) (int, error) {
	fmt.Println("--- :", b)
	bLength := len(b)
	fmt.Println("+++ :", bLength)
	if bLength > 0 {
		for i := range b {
			b[i] = 'A'
		}
		fmt.Println("... :", b)

		return bLength, nil
	} else {
		return 0, ErrEmptyBuffer(b)
	}
}

func main() {
	//reader.Validate(MyReader{})
	r := MyReader{}
	str := strings.NewReader("Hello, Reader!")
	c := make([]byte, 8)
	str.Read(c)
	_, err := r.Read(c)
	fmt.Println("pppp :",err)

	d := make([]byte, 0)
	_, err2 := r.Read(d)
	fmt.Println("pppp :",err2)
}

输出

--- : [72 101 108 108 111 44 32 82]
+++ : 8
... : [65 65 65 65 65 65 65 65]
pppp : 
--- : []
+++ : 0
pppp : cannot read empty buffer

你可能感兴趣的:(Go,golang)