Last active
August 29, 2015 14:24
-
-
Save miku/9d4ec017eb459c9c573e to your computer and use it in GitHub Desktop.
String implementing io.Reader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
hello |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://play.golang.org/p/ejpUVOx8jR | |
// https://medium.com/@mschuett/golangs-reader-interface-bd2917d5ce83 | |
package main | |
import "io" | |
import "io/ioutil" | |
import "log" | |
type Reader struct { | |
pos int | |
read string | |
} | |
func NewReader(toRead string) *Reader { | |
return &Reader{0, toRead} | |
} | |
func (r *Reader) Read(p []byte) (n int, err error) { | |
if r.pos == len(r.read) { | |
return 0, io.EOF | |
} | |
var c int | |
for i := r.pos; i < len(p); i++ { | |
if i >= len(r.read) { | |
break | |
} | |
p[i] = []byte(r.read)[r.pos] | |
r.pos++ | |
c++ | |
} | |
return c, nil | |
} | |
func main() { | |
M := NewReader("testtest") | |
stuff, err := ioutil.ReadAll(M) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("%s\n", string(stuff)) | |
N := NewReader("test") | |
b := make([]byte, 2) | |
N.Read(b) | |
log.Printf("%s", b) | |
// file, err := os.Open("hello") | |
// if err != nil { | |
// log.Fatal(err) | |
// } | |
// var b []byte | |
// file.Read(b) | |
// log.Printf("%v", b) | |
// b := make([]byte, 2) | |
// file.Read(b) | |
// log.Printf("%v", b) | |
// c := make([]byte, 3) | |
// file.Read(c) | |
// log.Printf("%v", c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment