anon
anon

Reputation:

How to discharge go channel without using received data?

I created a channel and want to discharge it without using received values. However, compiler doesn't allow me to write code like this:

for i := range ch {
// code
}

complains that i is unused

substituting _ for i doesn't work either

What is the idiomatic way to do it?

Upvotes: 2

Views: 117

Answers (3)

Havelock
Havelock

Reputation: 6966

You could use select instead of range:

for {
        select {
        // read and discard
        case <-ch:
        // to avoid deadlock
        default:
            continue
        }

    }

But then again, are you sure you really need the channel if you're not reading from it?

Upvotes: 2

Eugene Lisitsky
Eugene Lisitsky

Reputation: 12875

If you don't want to stuck in infinite loop read values until channel is not empty:

exitLoop:
for {
    select {
    case <-ch:
    default:
        break exitLoop
    }
}

Demo: https://play.golang.org/p/UsIqdoAGZi

If you need "updatable channel" - which keeps only 1 last value, you may use this recipe - https://stackoverflow.com/a/47107654/5165332

Upvotes: 0

wasmup
wasmup

Reputation: 16253

Try this:

package main

import (
    "fmt"
)

func main() {
    ch := make(chan int)
    close(ch)
    for range ch {
        fmt.Println("for")
    }
    fmt.Println("done")
}

output:

done

Upvotes: 2

Related Questions