Instantly share code, notes, and snippets.

What would you like to do?
Proposal to add ReaderFunc to package io
This programs generates 32 random bytes formatted à la "hexdump -C".
It does it in just 2 lines of code using the power of the standard library
and a trick to convert a func Read([]byte) (int, error) into an io.Reader.
Inspiration: see HandlerFunc in net/http
Note: on the Go Playground the seed is NOT random.
Author: Olivier Mengué
package main
import (
"math/rand" // alternative: "crypto/rand"
// ReaderFunc allows to convert an io.Reader.Read-like function into an io.Reader
type ReaderFunc func([]byte) (n int, err error)
// Read implements the io.Reader interface
func (read ReaderFunc) Read(p []byte) (int, error) {
return read(p)
func main() {
// Transform func rand.Read into an io.Reader
randReader := ReaderFunc(rand.Read)
// Read 32 bytes from randReader and dump in hex
io.CopyN(hex.Dumper(os.Stdout), randReader, 32)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment