iface_embed_promoted.mx raw

   1  // A type that satisfies an interface only by PROMOTION from an embedded
   2  // interface field has no method symbol of its own, so the dispatch arm for it
   3  // has to re-dispatch on the interface value the field holds. Without that arm
   4  // the type-ID matched nothing and every call panicked
   5  //
   6  //	interface dispatch: no impl for Accept (2 impl(s), none matches)
   7  //
   8  // net/http.(*Server).Serve hit it on every request: onceCloseListener embeds
   9  // net.Listener, so Accept is promoted while Close is declared.
  10  //
  11  // The declared method must still win over the promoted one of the same name.
  12  package main
  13  
  14  import (
  15  	"fmt"
  16  )
  17  
  18  type conn interface {
  19  	Accept() (n int32)
  20  	Close() (err error)
  21  }
  22  
  23  type listener struct {
  24  	count int32
  25  }
  26  
  27  func (l *listener) Accept() (n int32) {
  28  	l.count = l.count + 1
  29  	return l.count
  30  }
  31  
  32  func (l *listener) Close() (err error) {
  33  	return nil
  34  }
  35  
  36  // wrapper reaches Accept only by embedding conn; Close is declared here and
  37  // must dispatch to this one, not to the promoted listener.Close.
  38  type wrapper struct {
  39  	conn
  40  	tag int32
  41  }
  42  
  43  func (w *wrapper) Close() (err error) {
  44  	w.tag = w.tag + 100
  45  	return nil
  46  }
  47  
  48  func acceptVia(c conn) (n int32) {
  49  	return c.Accept()
  50  }
  51  
  52  func closeVia(c conn) (err error) {
  53  	return c.Close()
  54  }
  55  
  56  func main() {
  57  	// Termination: a batch program must still be stoppable, so the entry
  58  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  59  	select {
  60  	case <-shutdown:
  61  		return
  62  	default:
  63  	}
  64  
  65  	inner := &listener{count: 0}
  66  	w := &wrapper{conn: inner, tag: 7}
  67  	fmt.Printf("promoted-ptr=%d\n", acceptVia(w))
  68  	fmt.Printf("promoted-ptr-again=%d\n", acceptVia(w))
  69  	closeVia(w)
  70  	fmt.Printf("declared-close-tag=%d\n", w.tag)
  71  	v := wrapper{conn: inner, tag: 3}
  72  	fmt.Printf("promoted-value=%d\n", acceptVia(v))
  73  	fmt.Printf("inner-count=%d\n", inner.count)
  74  }
  75