Implementing the Reader type


A Reader type can be a struct as well in the strings packages.


The NewReader() takes in a string and returns a Reader type.
func NewReader(s string) *Reader
This almost explicitly converts a string to Reader type and is useful because then the methods are added right after it is converted.
whateverstring = strings.NewReader("whatever")This allows whateverstring to be the following in one line of code.
- string
- Reader type
- use Reader type methods io.Read ..ect
- use the strings packages methods as well
- This whateverstring then becomes a package in a sense.
You can use any of these methods on whateverstring.
fmt.Println(whateverstring.Replace(“This is <b>HTML</b>!”))
r := strings.NewReader(whateverstring)
b := r.Len()
https://play.golang.org/p/h5a7W55Xg6g


You can also implement the Writer type pretty much the same way.
type Writer interface {
Write(p []byte) (n int, err error)
}
There is also a package that implements the Writer type struct


w := bufio.NewWriter(os.Stdout)
fmt.Fprint(w, "Hello, ")
w.Flush()
The bufio.NewWriter takes in an io.writer and returns a writer type.
func NewWriter(w io.Writer) *Writer
This almost resembles the strings.NewReader() but different package and it does a bit different things.
You get different methods as well.


You begin to see this pattern of building Named types and easily implementing these types. You can even implement them both if you wanted and that was done in the standard package in some form.
As soon as you get the Writer type you can throw these methods right on it.
w.Flush()
w.Size()
If you want a method to utilize both then the standard library has that as well.


They have a good example of its use as well.
r := strings.NewReader(“some io.Reader stream to be read\n”)
if _, err := io.Copy(os.Stdout, r); err != nil {
log.Fatal(err)
}As you can tell from previous article that the NewReader converts the string to a Reader type with all its methods and the io.Copy is taking in a Writer type with os.Stdout as a Reader type in the io package. You can see you can build really complex type names and implement them freely together or as another type. This is part of the original Go magic I was referring to. By understanding these types you also get a look at the basics of the http package that utilizes both as well. We will explore further the io package in the next article.