2

How do I embed a channel in a struct in Go?

Why the inconsistency between the map syntax:

var m map[string]int

and channel,

var m chan int

?

To clarify, in Go it is possible to embed a type in another type. The embedder type gains access to all the methods defined on the embedded type, but it is also possible to refer to the embedded type explicitly by the name of its type. Therefore, the inconsistency between the map type declaration and channel type declaration is confusing for someone who would like to refer to an embedded channel type.

ealfonso
  • 6,622
  • 5
  • 39
  • 67
  • 4
    @rightfold: Care to chime in on the meta-question about this? http://meta.stackoverflow.com/questions/272814/what-is-so-wrong-with-my-question-about-structs-in-go (Not that there isn't already quite a lot of feedback.) – Deduplicator Oct 04 '14 at 15:53
  • There's a similar question here: [Go: Embedding a primitive type?](http://stackoverflow.com/q/38811253/142239) – Siu Ching Pong -Asuka Kenji- Aug 16 '16 at 22:36

1 Answers1

10

The problem is that embedding allows you mainly to benefit from the methods from the embedded type (as mentioned in "Embedding instead of inheritance in Go")

And channel, like map, is an unnamed type (specified using a type literal, which composes a new type from existing types.).
It doesn't have methods of its own, or exported fields, so you wouldn't go very far by embedding a channel type within a struct {}.

You would probably have an error message similar as the one in this example:

func (x chan int) m2() {}
invalid receiver type chan int (chan int is an unnamed type)

If embedding a channel type within a struct type worked, that unnamed type would be able to act as a receiver for methods, which doesn't seem to be allowed by the language in the first place.

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 2
    Thanks for actually making an effort to understand the question and to provide a meaningful answer. The reason I was hoping to embed a channel was, for instance, to be able to receive or send directly to the embedder of channel, instead of having to refer to it explicitly. But I guess this doesn't work for built-in operations that aren't methods on a named type. Thanks for your answer. – ealfonso Oct 04 '14 at 16:17
  • 2
    @erjoalgo indeed, that was a valid request (I never thought to actually try and embed a `channel` type within a `struct` type). But the way those unamed types are used, that wouldn't work well. – VonC Oct 04 '14 at 16:19
  • 2
    Yeah. What I was doing was implementing a custom channel with methods on top of it, but it would have been nice if my custom channel could embed a channel and directly receive/send with the `c<-1` syntax. Currently, I have to do `c.c-1`, which looks less elegant. – ealfonso Oct 04 '14 at 16:30
  • 1
    @erjoalgo I just edited the answer to add the "invalid receiver type" error message. – VonC Oct 04 '14 at 16:30