diff options
author | MaurĂcio Antunes <mauricio.abreua@gmail.com> | 2024-02-14 15:53:54 -0300 |
---|---|---|
committer | MaurĂcio Antunes <mauricio.abreua@gmail.com> | 2024-02-14 15:53:54 -0300 |
commit | dac11a225d6ba9411de722b138284a534e46afaa (patch) | |
tree | 953e5f630db47f0fda8ce2460599106749b72518 | |
parent | 749202cda06921d9304ad804b11808ffba485c6a (diff) |
feat: One more concurrency exercise
-rw-r--r-- | exercises/concurrent/concurrent3/main_test.go | 43 | ||||
-rw-r--r-- | info.toml | 12 |
2 files changed, 55 insertions, 0 deletions
diff --git a/exercises/concurrent/concurrent3/main_test.go b/exercises/concurrent/concurrent3/main_test.go new file mode 100644 index 0000000..4a7cf33 --- /dev/null +++ b/exercises/concurrent/concurrent3/main_test.go @@ -0,0 +1,43 @@ +// concurrent3 +// Make the tests pass! + +// I AM NOT DONE +package main_test + +import ( + "bytes" + "fmt" + "testing" +) + +func TestSendAndReceive(t *testing.T) { + var buf bytes.Buffer + + messages := make(chan string) + sendAndReceive(&buf, messages) + + got := buf.String() + want := "Hello World" + + if got != want { + t.Errorf("got %q want %q", got, want) + } +} + +func sendAndReceive(buf *bytes.Buffer, messages chan string) { + go func() { + messages <- "Hello" + messages <- "World" + close(messages) + }() + + greeting := <-messages + fmt.Fprint(buf, greeting) + + // Here we just receive the first message + // Consider using a for-range loop to iterate over the messages + _, ok := <-messages + if !ok { + fmt.Fprint(buf, "Channel is closed") + } +} @@ -342,3 +342,15 @@ A counter is a good example. Your counter could be updated with a different valu Read a little about mutexes: https://pkg.go.dev/sync#Mutex. """ + +[[exercises]] +name = "concurrent3" +path = "exercises/concurrent/concurrent3/main_test.go" +mode = "test" +hint = """ +Writing messages to closed channels will panic. + +To avoid panics, we don't want to send messages to closed channels. + +Remember: channels can be iterated using for-range loops. +""" |