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
相关推荐
bing.shao2 小时前
golang 做AI任务链的优势和场景
开发语言·人工智能·golang
源代码•宸3 小时前
Golang原理剖析(Map 源码梳理)
经验分享·后端·算法·leetcode·golang·map
龙门吹雪5 小时前
GO 语言处理多个布尔选项的实现方案
开发语言·后端·golang·布尔选项·标识位
源代码•宸5 小时前
Golang原理剖析(map面试与分析)
开发语言·后端·算法·面试·职场和发展·golang·map
AC赳赳老秦7 小时前
技术文档合著:DeepSeek辅助多人协作文档的风格统一与内容补全
android·大数据·人工智能·微服务·golang·自动化·deepseek
Grassto8 小时前
9 Go Module 依赖图是如何构建的?源码解析
开发语言·后端·golang·go module
bing.shao8 小时前
基于 Go + Ollama 开发智能日志分析工具完整实战
开发语言·后端·golang
Hello.Reader9 小时前
连接四元组它为什么重要,以及它和端口复用(SO_REUSEPORT)的关系(Go 实战)
开发语言·后端·golang
浮尘笔记10 小时前
Go语言上下文:context.Context类型详解
开发语言·后端·golang
weixin1997010801610 小时前
安家 GO item_area - 获取地区类列表数据接口对接全攻略:从入门到精通
java·数据库·golang