I tried to implement a very trivial io.Reader
in Go:
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
// Very trivial function I implemented.
func (r *rot13Reader) Read(p []byte) (int, error) {
return 5, nil // Return some trivial values for now.
}
func main() {
s := strings.NewReader(
"Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
In the end, I want rot13Reader
to apply ROT13 to the string that it is reading, but for now, I am just trying to create a very trivial io.Reader
that matches the proper interface.
When I run this program, it never halts. Why? Where do I have an infinite loop?
Update: I tried altering the data
splice via the for loop below, but it doesn't seem to actually alter the splice. Do I need to somehow copy over data
?
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func (r *rot13Reader) Read(data []byte) (int, error) {
bytesRead, err := r.r.Read(data)
// Try to alter data... only without this for loop, text prints in standard output... odd.
for i := 0; i < bytesRead; i++ {
data[i] += 13
}
return bytesRead, err
}
func main() {
s := strings.NewReader(
"Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}