Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The scope of break and continue in golang select is strange #43889

Closed
guonaihong opened this issue Jan 25, 2021 · 4 comments
Closed

The scope of break and continue in golang select is strange #43889

guonaihong opened this issue Jan 25, 2021 · 4 comments

Comments

@guonaihong
Copy link

code 1

// output: 0 1 2 4 
package main

import (
	"fmt"
)

func main() {

	data := make(chan int)
	go func() {
		for i := 0; i < 5; i++ {
			data <- i
		}
		close(data)
	}()

	for {
		v := 0
		ok := true
		select {
		case v, ok = <-data:
			if v == 3 {
				continue
			}

			if !ok {
				return
			}

		}
		fmt.Printf("v :%d\n", v)
	}
}

code 2

replace continue with break

//output: 0 1 2 3 4 
package main

import (
	"fmt"
)

func main() {

	data := make(chan int)
	go func() {
		for i := 0; i < 5; i++ {
			data <- i
		}
		close(data)
	}()

	for {
		v := 0
		ok := true
		select {
		case v, ok = <-data:
			if v == 3 {
				break
			}

			if !ok {
				return
			}

		}
		fmt.Printf("%d ", v)
	}
}

why

break affects select, continue affects for. This is easy to confuse people, why was it designed like this in the first place

@mdempsky
Copy link
Member

Unlike many projects, the Go project does not use GitHub Issues for general discussion or asking questions. GitHub Issues are used for tracking bugs and proposals only.

For asking questions, see:

If we closed your issue as a question with a link to this wiki, we apologize. Please ask the question on one of the above forums.

@guonaihong
Copy link
Author

My question is about semantics. It is difficult to answer if it is not the person who made the decision.

@guonaihong
Copy link
Author

What I am curious about is why it is designed like this.

@mdempsky
Copy link
Member

Please ask your question on one of the above forums.

@golang golang locked and limited conversation to collaborators Jan 25, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants