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

Replace T type with a truly generic one in the "How to Gracefully Close Channels" article #251

Open
GCrispino opened this issue Mar 25, 2023 · 2 comments

Comments

@GCrispino
Copy link
Contributor

GCrispino commented Mar 25, 2023

Hello everybody!

Now that we have generics, I believe we could leverage them in code examples like the below, in the "How to Gracefully Close Channels" article:

package main

import "fmt"

type T int

func IsClosed(ch <-chan T) bool {
	select {
	case <-ch:
		return true
	default:
	}

	return false
}

func main() {
	c := make(chan T)
	fmt.Println(IsClosed(c)) // false
	close(c)
	fmt.Println(IsClosed(c)) // true
}

This could be rewritten to:

package main

import "fmt"

func IsClosed[T any](ch <-chan T) bool {
	select {
	case <-ch:
		return true
	default:
	}

	return false
}

func main() {
	c := make(chan struct{})
	fmt.Println(IsClosed(c)) // false
	close(c)
	fmt.Println(IsClosed(c)) // true
}

Another example would be the following code sample in the same article:

func SafeClose(ch chan T) (justClosed bool) {
	defer func() {
		if recover() != nil {
			// The return result can be altered
			// in a defer function call.
			justClosed = false
		}
	}()

	// assume ch != nil here.
	close(ch)   // panic if ch is closed
	return true // <=> justClosed = true; return
}

That could be rewritten to:

func SafeClose[T any](ch chan T) (justClosed bool) {
	defer func() {
		if recover() != nil {
			// The return result can be altered
			// in a defer function call.
			justClosed = false
		}
	}()

	// assume ch != nil here.
	close(ch)   // panic if ch is closed
	return true // <=> justClosed = true; return
}

This is just an idea, I can see points being made to either accept it or not, so I'm just leaving it here in case you find it useful 🙂

@go101
Copy link
Owner

go101 commented Mar 25, 2023

@GCrispino
Thanks for the suggestion. I think it is good and would be perfect when Go custom generics are used more popularly later.
At the moment, I don't want the generic thing distract reader's attentions.

So, let's hold the suggestion now.

@GCrispino
Copy link
Contributor Author

@go101 Sure! Thanks for answering. Feel free to close the issue if you'd like

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