-
Notifications
You must be signed in to change notification settings - Fork 17.9k
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
proposal: core/generics: allow slices/arrays of not initialized constraints #50758
Comments
I'm sorry, I don't understand what you are proposing. Where is |
type Indexable[T any] interface {
[]T | string
}
func Len[T Indexable[E], E any](v T) int {
return len(v)
}
Edit: Hold on. I think that I just realized what you're asking for. You want to be able to use a constraint directly as an element type, correct? So you want to be able to do type Indexable interface {
[]any | string
}
func Len[T Indexable](v T) int {
return len(v)
} Is that right? That's not going to work. With that syntax, there's no way for the compiler to know if you want a literal slice of |
I see, that makes sense. I tough that a slice where the elements satisfy interface{} was going to work in all cases, that is why I wrote something like this. test2([]int{1,2,3}) // it works
test2([]any{1,2,3}) // still works But did not realize that maybe someone wants his type to be literally of type "[]interface{}" which is completely valid. I still don't feel this is right or readable code. type basicPrimitiver interface {
int | float64
}
type foo[T basicPrimitiver] interface {
[]T | string
}
// ...
test[int]("hello")
// or
test[float64]("hello") You are practically writing random types, so the type inference don't bother you. Possibly the type inference should check that if it can't determinate the type, it will try to check if it satisfies the rest of the types.
|
Although type foo interface {
any
} So this is an inconsistency. |
With the actual implementation, if we want to create a function that receive a generic slice, we would write something like this:
A generic slice with more types:
I think this situation could be improved.
One way is to allow not initialized constraints with slices and arrays.
If I have understood (https://go.dev/doc/faq#convert_slice_of_interface) correctly, in case someone tries to use the interface like a regular interface instead of a constraint for generics, the compilation will fail
Maybe another less aggressive solution would be to have smarter type inference for these cases, so in the first example ...
... would be enough.
The text was updated successfully, but these errors were encountered: