types - Switch interface implementation without overhead -
given interface , 2 (or more) implementations struggle switch implementation when extending functionality.
for illustration assume there interface inumber supports inc , string , 2 implementations numberint32 , numberint64 obvious implementation. assume want implement evencounter on top of inumber. evencounter has inctwice , shall phone call inc twice. struggle types right without using struct surrounding inumber in evencounter.
type inumber interface { inc() string() string } type numberint32 struct { number int32 } func newnumberint32() inumber { ret := new(numberint32) ret.number = 0 homecoming ret } func (this *numberint32) inc() { this.number += 1 } func (this *numberint32) string() string { homecoming fmt.sprintf("%d", this.number) } // type numberint64.... // obvious
here struggle
type evencounter1 inumber // nope, additional methods not possible type evencounter2 numberint32 // nope func (this *evencounter2) inctwice() { i:=0; < 2; i+=1 { // this.inc() // inc not found // inumber(*this).inc() // cannot convert // in, ok := *this.(inumber) // cannot convert // v, ok := this.(inumber) // cannot convert // concrete conversion a) not work , b) won't help // here should generic // v, ok := this.(numberint32) // how phone call inc here on this? } }
just embedding in struct works...
type evencounter3 struct { n inumber } func (this *evencounter3) inctwice() { n := this.n // step want avoid n.inc() // using this.n.inc() twice makes slower n.inc() } func (this *evencounter3) string() string { homecoming this.n.string() }
i live need implement delegation manually each method, want rely on inumber , not specific implementation (that mean changing lots of places seek implementation, however, want avoid indirection , (most likely?) space. there way avoid struct , straight evencounter (specific) inumber additional methods?
btw real illustration set of integers , map of integers integers millions of instances intertwined (and no, map[int]bool won't suffice - slow, bitset interesting depening on utilize case, etc.) , testing different implementations of set , map changing 2-3 lines in code (ideally type , maybe generic creation of instances resp. making copies)
any help appreciated , hope hasn't been asked yet...
your variant using embedding not embed. embedded fields anonymous , go delegates automatically.
this simplifies illustration to:
type evencounter3 struct { inumber } func (this *evencounter3) inctwice() { this.inc() // using this.n.inc() twice makes slower this.inc() }
note string() automatically delegated ("promoted" in go speak).
as calling inc() twice making slower, well, that's limitation of using interfaces. point of interface not expose implementation, cannot access internal number variable.
types interface go implementation
No comments:
Post a Comment