Ambiguous Conversion Syntax in Go -


i have following type definition:

type reader io.reader 

and want reader type implement io.reader interface, do:

func (r reader) read(p []byte) (n int, err error) {     return io.reader(r).read(p) } 

the problem this: io.reader(r) mean 1 of 2 things:

  • convert r underlying type (io.reader)
  • assert statically (checked compiler) r satisfies io.reader interface (since we've defined read([]byte) (int, error) method, does). create new io.reader interface value , store r inside it.

i want former happen. if latter happens, when call io.reader(r).read(p), call r's underlying read method (which inside @ moment), , infinite loop. like happen extract underlying io.reader inside r, , use its read method.

of course, test see in practice of 2 of these happens, i'm curious in general how these problems resolved go compiler. couldn't find relevant information in language spec.

you can't use interface type reader defined io.reader receiver type in func (r reader) {}.

you need define reader type specific type

type reader struct {     // stuff } 

to answer question, io.reader(r) means assert @ compile time r satisfies io.reader interface , create new io.reader interface value , store r inside it. (your second choice).

so if try above you'll infinite recursion.

the idea of underlying io.reader makes no sense in go since can't define methods on interfaces, on concrete types.

you can of course embed types within each other might this

type reader struct {     other io.reader } 

which call

func (r reader) read(p []byte) (n int, err error) {     return r.other.read(p) } 

Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -