select Flashcards

(11 cards)

1
Q

Basic select

A

Syntax:

select {
case msg := <-ch1:
    fmt.Println(msg)
case ch2 <- data:
    fmt.Println("sent")
}

Behavior:
* Blocks until one case can proceed
* Random selection if multiple cases ready

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Non-Blocking select

A

Using default:

select {
case val := <-ch:
    fmt.Println(val)
default:
    fmt.Println("no value ready")
}

Use Case: Poll channels without blocking

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Timeout Pattern

A

With time.After:

select {
case res := <-longOperation():
    fmt.Println(res)
case <-time.After(1 * time.Second):
    fmt.Println("timeout!")
}

Key Point: Creates a temporary channel

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Empty select

A

Blocks forever:

select {}  // Equivalent to: for {}

Use Case: Prevent main() from exiting (rare)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Priority Selection

A

Immediate vs Fallback:

select {
case job := <-priorityQueue:
    process(job)
default:
    select {
    case job := <-normalQueue:
        process(job)
    case <-time.After(10 * time.Millisecond):
        fmt.Println("idle")
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Combined with for

A

Continuous Monitoring:

~~~
for {
select {
case msg := <-msgCh:
handle(msg)
case <-stopCh:
return // Exit loop
}
}```

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

nil Channels

A

Behavior:
* Sends/receives on nil channels never execute
* Useful for disabling cases dynamically:

var dataCh chan Data  // nil initially

select {
case data := <-dataCh:  // Skipped
    process(data)
case <-time.After(1 * time.Second):
    fmt.Println("no data channel")
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Multiple Actions

A

Single Case:

select {
case val := <-ch:
    fmt.Println(val)
    fallthrough  // Rarely used!
case <-time.After(0):
    fmt.Println("always runs after first case")
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Common Pitfalls

A

❌ Forgetting default → deadlock risk
❌ Unbalanced channel operations → leaks
❌ Ignoring ok when checking closed channels

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Real-World Patterns

A
  1. Fan-in:
select {
case v := <-source1:
    out <- v
case v := <-source2:
    out <- v
}
  1. Graceful Shutdown:
select {
case <-workDone:
    fmt.Println("completed")
case <-ctx.Done():
    fmt.Println("cancelled")
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Golden Rules

A
  1. select is Go’s switch for channels
  2. Always handle all possible cases
  3. Use timeouts to prevent deadlocks
  4. nil channels are useful for dynamic control
How well did you know this?
1
Not at all
2
3
4
5
Perfectly