A Tour of Go部分练习

文章目录

    • [Reader 练习](#Reader 练习)

Reader 练习

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

实现io.Reader接口

go 复制代码
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)
}

输出

text 复制代码
--- : [72 101 108 108 111 44 32 82]
+++ : 8
... : [65 65 65 65 65 65 65 65]
pppp : <nil>
--- : []
+++ : 0
pppp : cannot read empty buffer
相关推荐
dancing9991 小时前
Golang的linux运行环境的安装与配置
linux·服务器·golang
muxue1781 小时前
go语言封装、继承与多态:
开发语言·后端·golang
开心码农1号1 小时前
Go语言中 源文件开头的 // +build 注释的用法
开发语言·后端·golang
北极象1 小时前
Go主要里程碑版本及其新增特性
开发语言·后端·golang
在成都搬砖的鸭鸭2 小时前
【Go底层】http标准库服务端实现原理
开发语言·http·golang
Lu Yao_5 小时前
golang -- 如何获取变量类型
android·java·golang
码出钞能力7 小时前
对golang中CSP的理解
开发语言·后端·golang
HelloZheQ1 天前
Go:简洁高效,构建现代应用的利器
开发语言·后端·golang
非晓为骁1 天前
【Go】优化文件下载处理:从多级复制到零拷贝流式处理
开发语言·后端·性能优化·golang·零拷贝
北极象1 天前
Golang中集合相关的库
开发语言·后端·golang