Skip to content

Check against for x := range <-ch? #28

@ainar-g

Description

@ainar-g

An interesting gotcha I found recently, which could be dangerous in overly-dynamically-typed code:

ch := make(chan []int, 3)
ch <- []int{10, 20, 30}
close(ch)

for s := range <-ch {
        fmt.Println(s)
}

As opposed to:

[10 20 30]

This prints:

0
1
2

Because what the user actually wanted to write is probably:

for s := range ch {
        fmt.Println(s)
}

Without the <-.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions