Channel Interface Type

1,335 views
Skip to first unread message

Rick

unread,
Jun 17, 2011, 5:52:01 PM6/17/11
to golang-nuts, rmor...@fedroot.com
Hi all,
I've been refactoring the CodeWalk "Share Memory by
Communicating" (http://golang.org/doc/codewalk/sharemem/) as an
exercise to get my feet wet in Go. I've run into a problem with the
declaration of channels using an interface type and hope someone can
set me straight. Here are the details.

I have created a Pollable interface:

type Pollable interface {
AddToQueue(pending chan Pollable)
Poll() string
GetId() string
Requeue(pending chan Pollable)
}

And a Resource type that implements the Pollable interface. The
Resource type has the following constructor:

func NewResource(url string) *Resource {
return &Resource{url: url}
}

and the following implementation of method AddToQueue:

func (resource *Resource) AddToQueue(pending chan<- *Resource) {
pending <- resource
}

For now we can ignore the other methods in Resource.

Here is the modified main.go from the Codewalk:

package main

import (
"monitor"
)

const (
numPollers = 3 // number of Poller goroutines to launch
second = 1e9 // one second is 1e9 nanoseconds
statusInterval = 10 * second // how often to log status to stdout
)

// the resources to poll
var urls = []string{
"http://www.google.com/",
"http://golang.org/",
"http://blog.golang.org/",
"https://juliaswild.com/",
}


func main() {
// create pending and done channels
pending, done := make(chan monitor.Pollable), make(chan
monitor.Pollable)

// launch the StateMonitor
status := monitor.StateMonitor(statusInterval)

// launch some Poller goroutines
for i := 0; i < numPollers; i++ {
go monitor.Poller(pending, done, status)
}

// send some Resources to the pending queue
for _, url := range urls {
resource := monitor.NewResource(url)
go resource.AddToQueue(pending) // ** Line 40
** //
}

// pull resources from the done queue and put them back on pending
for resource := range done {
go resource.Requeue(pending)
}
}

The monitor package that main relies on compiles successfully, but
main.go fails to compile with the following solitary error:

main.go:40: cannot use pending (type chan monitor.Pollable) as type
chan<- *monitor.Resource in function argument

What am I doing wrong, folks?

Rick





jimmy frasche

unread,
Jun 17, 2011, 6:00:44 PM6/17/11
to Rick, golang-nuts, rmor...@fedroot.com
> main.go:40: cannot use pending (type chan monitor.Pollable) as type
> chan<- *monitor.Resource in function argument

Interfaces are literal. If the interface says Pollable so it has to be
Pollable. The compiler can't figure out that, if it replaced *Resource
with Pollable in the chan type, then *Resource satisfies Pollable. It
just looks and sees that the types don't match exactly and stops.

Reply all
Reply to author
Forward
0 new messages