Skip to content

Eun/go-prioselect

Repository files navigation

go-prioselect Travis Codecov GoDoc go-report

golangs select with a priority order.

Description

Golangs select is not respecting the order.
Therefore in some cases it might happen that you want to prioritize specific channels over others when data is following in at the same time.
You can use the native approach:

channel1 := make(chan int)
channel2 := make(chan int)
channel3 := make(chan int)
// ...
// Prioritize channel1 over channel2 and channel3
// so try to read from channel1 first
select {
    case v := <-channel1:
        // do something with v from channel1
		return
	default:
		// continue with next select
}
// if there is no data try channel2
select {
	case v := <-channel2:
        // do something with v from channel2
        return
    default:
        // continue with next select
}
// if there is no data try all and wait until one succeeds
select {
    case v := <-channel1:
        // do something with v from channel1
        return
	case v := <-channel2:
        // do something with v from channel2
        return
    case v := <-channel3:
        // do something with v from channel3
        return
}

Or you could use prioselect.Select:

channel1 := make(chan int)
channel2 := make(chan int)
channel3 := make(chan int)
// ...
// Prioritize channel1 over channel2 and channel3
value, channel := prioselect.Select(channel1, channel2, channel3)
switch channel {
    case channel1:
         case v := <-channel1:
        // do something with v from channel1
        return
	case channel2:
        // do something with v from channel2
        return
    case channel3:
        // do something with v from channel3
        return
}

Other examples in example_test.go

Installation

go get github.com/Eun/go-prioselect

About

golangs select with a priority order.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages