Skip to content

Instantly share code, notes, and snippets.

@rndD
Last active July 22, 2025 13:16
Show Gist options
  • Save rndD/5ba3c7c9883de396a4ea to your computer and use it in GitHub Desktop.
Save rndD/5ba3c7c9883de396a4ea to your computer and use it in GitHub Desktop.
A tour of Go: Exercise: Readers
package main
import "code.google.com/p/go-tour/reader"
type MyReader struct{}
func (r MyReader) Read(bytes []byte) (int, error) {
for i := range bytes {
bytes[i] = 65
}
return len(bytes), nil
}
// TODO: Add a Read([]byte) (int, error) method to MyReader.
func main() {
reader.Validate(MyReader{})
}
@psydvl
Copy link

psydvl commented Aug 12, 2021

package main

import "golang.org/x/tour/reader"

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

type MyReader struct{}
type MyReaderError bool

func (MyReaderError) Error() string {
	return "too short b capacity"
}

func (MyReader) Read(b []byte) (int, error) {
	if cap(b) < 1 {
		return 0, MyReaderError(true)
	}
	b[0] = 'A'
	return 1, nil
}

func main() {
	reader.Validate(MyReader{})
}

@krapie
Copy link

krapie commented Dec 9, 2022

package main

import "golang.org/x/tour/reader"

type MyReader struct{}
type MyReaderError int

func (e MyReaderError) Error() string {
	return "capacity max error, cap: " + string(e)
}

// TODO: Add a Read([]byte) (int, error) method to MyReader.
func (myReader MyReader) Read(b []byte) (int, error) {
	if cap(b) < 1 {
		return 0, MyReaderError(cap(b))
	}
	
	b[0] = 'A'
	return 1, nil
}

func main() {
	reader.Validate(MyReader{})
}

@kwe92
Copy link

kwe92 commented Sep 22, 2023

The description of the problem didn't make sense to me. Thank you for the solution.

@rndD
Copy link
Author

rndD commented Sep 24, 2023

The description of the problem didn't make sense to me. Thank you for the solution.

You are welcome

@jm-janzen
Copy link

This is much nicer than what I had. I just stubbed in the following and was surprised when it actually passed lol!

func (r MyReader) Read(b []byte) (int, error) {
	b[0] = 'A'
	return 1, nil
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment