-
Notifications
You must be signed in to change notification settings - Fork 18k
proposal: context: implement NewContext and FromContext with generics #57025
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
Comments
See also #49189. |
CC @neild |
Maybe we can add a helper function: func DoIfValid[T any, V interface {
*T
Valid() bool
}](ctx Context, fn func(v *T)) {
if v := FromContext[T](ctx); V(v).Valid() {
fn(v)
}
} |
Better naming: context.ValueInto[T any](parent Context, v *T) Context
context.ValueFrom[T any](ctx Context) *T |
I don't see the benefit of The |
@Sajmani Thanks for your comment. It can simplify code for so many go apps, even the go source itself. Here is a example, people must to define a private type, a private variable as context key and two functions to manipulate it: Line 142 in 8bcc490
We can now eliminate these duplicate code definitions if golang provides a generic version. Also, I think this is one of the best examples of using generics. |
it maybe returns a bool to indicate the assertion fails. I just don't think it's necessary. A nil *T can indicate assertion fails. context.ValueFrom[T any](ctx Context) (*T, bool) |
I see: this function associates a value with a context using the value's The problem with this is that two packages that are unaware of each other might try to associate the same type with a context, such as a Logger or database handle. If the programmer is not aware of this possibility, this could lead to very strange bugs. We could provide guidance that this feature should only be used with a package's own types, but I think many people will be tempted by the convenience to misuse this feature. In my opinion the risks outweigh the benefits, but I'm willing to hear from others. |
@ianlancetaylor @dsnet @neild I have used it in my projects: https://github.com/ldclabs/ldvm/blob/main/util/value/context.go#L12 https://github.com/teambition/gear/blob/master/context.go#L41 |
I don't see a lot of support for this proposal, and it can be implemented outside of the standard library. Perhaps it should be an external package for now, and we can consider adopting it into the standard library if it sees wide use. |
This proposal has been declined as retracted. |
We can implements a very concisely NewContext and FromContext functions with generics:
It will be very useful:
The text was updated successfully, but these errors were encountered: