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

Why Async doesn't close a chan? #436

Open
yonesko opened this issue Mar 12, 2024 · 1 comment
Open

Why Async doesn't close a chan? #436

yonesko opened this issue Mar 12, 2024 · 1 comment

Comments

@yonesko
Copy link

yonesko commented Mar 12, 2024

// Async executes a function in a goroutine and returns the result in a channel.
func Async[A any](f func() A) <-chan A {
	ch := make(chan A, 1)
	go func() {
		ch <- f()
	}()
	return ch
}

Why Async doesn't close the chan?

@ivila
Copy link

ivila commented Jun 3, 2024

Because the chan could be garbage collected automatically when no one cares about it.
the chan have capacity of 1 due to its declaration

ch := make(chan A, 1)

so the method f must can pass value into this chan without any blocking, and after passing value into the chan, the method cares the chan no more.

        // this line of code must can execute
	go func() {
		ch <- f()
	}()

and if anyone listening to the chan outside, they can read it, after they stop reading, then there is no one cares about the chan anymore, in that case, the chan will be garbage collected automatically

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants