Created
April 25, 2017 17:06
-
-
Save elmiomar/16003c13dec80053d804db786615d9a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
type sender struct { | |
ch chan string | |
} | |
func (s *sender) send(msg string) { | |
s.ch <- msg | |
} | |
type receiver struct { | |
ch chan string | |
} | |
func (r *receiver) recv() { | |
for { | |
msg := <-r.ch | |
fmt.Println("received:", msg) | |
} | |
} | |
func connect(s *sender, r *receiver) { | |
ch := make(chan string) | |
s.ch, r.ch = ch, ch | |
} | |
func disconnect(s *sender, r *receiver) { | |
// What to do here? | |
// close channel? this panics | |
// close(s.ch) | |
// or set channel to nil? this doesn't | |
s.ch, r.ch = nil, nil | |
} | |
func main() { | |
s := &sender{} | |
r := &receiver{} | |
connect(s, r) | |
go r.recv() | |
go func() { | |
for { | |
s.send("Hi there!") | |
time.Sleep(time.Second * 1) | |
} | |
}() | |
time.Sleep(time.Second * 3) | |
disconnect(s, r) | |
// wait for user input | |
var input string | |
fmt.Scanln(&input) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment