Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

An idiomatic way to approach this would be to define a new interface, let's call it Bytes with a Bytes() []byte method.

Your function would accept an io.Reader but then the function body would typeswitch and check if the argument implements the Bytes interface. If it does, then call the Bytes() method. If it doesn't then call io.ReadAll() and continue to use the []byte in the rest of the impl.

The bytes.Buffer type already implements this Bytes() method with that signature. By the rules of Go this means it will be treated as an implementation of this Bytes interface, even if nobody defined that interface yet in the stdlib.

This is an example of Go's strong duck typing.



That's really interesting, thank you for explaining that! Somehow I've never thought to implement interferences to describe types that already exist.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: