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
相关推荐
我的golang之路果然有问题9 小时前
ElasticSearch+Gin+Gorm简单示例
大数据·开发语言·后端·elasticsearch·搜索引擎·golang·gin
钟离墨笺16 小时前
Go语言学习-->第一个go程序--hello world!
开发语言·学习·golang
march of Time16 小时前
go的工具库:github.com/expr-lang/expr
开发语言·golang·github
fashia19 小时前
Java转Go日记(五十七):gin 中间件
开发语言·后端·golang·go·gin
余厌厌厌20 小时前
go语言学习 第5章:函数
开发语言·学习·golang·go
YGGP20 小时前
吃透 Golang 基础:数据结构之 Struct
开发语言·数据结构·golang
钟离墨笺20 小时前
Go语言学习-->项目中引用第三方库方式
开发语言·学习·golang
heart000_11 天前
Go语言基础知识总结(超详细整理)
开发语言·后端·golang
白总Server1 天前
Golang 依赖注入:构建松耦合架构的关键技术
linux·运维·服务器·macos·架构·golang·xcode
钟离墨笺1 天前
Go语言学习-->编译器安装
开发语言·后端·学习·golang