io.Readerwhen we've opened files, encoded JSON and various other common tasks. It's a simple abstraction over reading data from something
io.Readeryou can gain a lot of re-use from the standard library, it's a very commonly used abstraction (along with its counterpart
contextto provide cancellation. This is especially useful if you're performing tasks which may be computationally expensive and you want to be able to stop them.
io.Readeryou have no guarantees over speed, it could take 1 nanosecond or hundreds of hours. You might find it useful to be able to cancel these kind of tasks in your own application and that's what Mat and David wrote about.
io.Reader) to solve this problem.
io.Readerso it can be cancelled.
io.Readeryou're usually supplying it to some other function and you dont really concern yourself with the details; such as
io.Readerwith "ABCDEF", when I send a cancel signal half-way through I when I try to continue to read I get nothing else so all I get is "ABC"
Readmethod will read the contents it has into a
bytethat we supply.
io.Readerfrom a string with some data
io.Readerwe pass in
io.Readerand this test will give us confidence as we move forward.
context.Contextwith cancellation so we can
cancelafter the first read
ctxto our function
cancelnothing was read
io.Readerthat we read from and the
context.Contextso let's create that and try and return it from our function instead of the original
io.Reader) so let's add the method.
context.Contextto see if it has been cancelled.
context.Context. This allows callers of the code to inspect the various reasons cancellation has occurred and this is covered more in the original post.
In software engineering, the delegation pattern is an object-oriented design pattern that allows object composition to achieve the same code reuse as inheritance.