Sitemap
Suman Chapai

Suman Chapai

Sleek. Go

2 min readSep 3, 2023

--

Go’s source code is always so sleek. This mostly comes from the Unix-y authors who like the Go authors and their relatives were mostly Electrical engineers… thus the procedural code with tricks and elegance, i suppose. Similar is Brian Kernighan’s code (relative of Go, Unix, C, etc.)

Get Suman Chapai’s stories in your inbox

Join Medium for free to get updates from this writer.

For example, I was writing the the implementation of the LimitReader function. A function that takes a reader and a max number of bytes to read and returns another reader that after reading n bytes returns EOF.

Press enter or click to view image in full size

Here was my version

type limitedReader struct {
innerReader io.Reader
read int64
readLimit int64
}

func LimitReader(r io.Reader, n int64) io.Reader {
return &limitedReader{r, 0, n}
}

func (l *limitedReader) Read(p []byte) (int, error) {
if l.read >= l.readLimit {
return 0, io.EOF
}
remainingLimit := int(l.readLimit - l.read)
if len(p) > remainingLimit {
p = p[:remainingLimit]
}
n, err := l.innerReader.Read(p)
l.read += int64(n)
return n, err
}

Then I looked at the source code of Go to see how they had done it.

func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n} }

// A LimitedReader reads from R but limits the amount of
// data returned to just N bytes. Each call to Read
// updates N to reflect the new amount remaining.
// Read returns EOF when N <= 0 or when the underlying R returns EOF.
type LimitedReader struct {
R Reader // underlying reader
N int64 // max bytes remaining
}

func (l *LimitedReader) Read(p []byte) (n int, err error) {
if l.N <= 0 {
return 0, EOF
}
if int64(len(p)) > l.N {
p = p[0:l.N]
}
n, err = l.R.Read(p)
l.N -= int64(n)
return
}

The idea is the same, but they only used two variables in the struct. Their variable naming convention is also succinct. It’s just so much Unix-y. Their code is always clever. And when I checked the git blame, i found, obviously that it was mostly Rob’s havoc.

Just in case, you’re wondering about the trick that’s going on in both of these programs, it’s the fact that we’re reducing the size of the slice where the bytes are read into because the size of the slice limits how much can be read into it.

--

--