-
Notifications
You must be signed in to change notification settings - Fork 17.6k
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: slices: add Of function #61213
Comments
As you say, I can't see anybody using this rather than |
I would argue the opposite: you would have to write slices.Of(&somepackage.NameThatIsRatherLong{...}, &somepackage.NameThatIsRatherLong{...}) when you could just write []*somepackage.NameThatIsRatherLong{{...}, {...}} Compared to writing a slice literal, |
Right, something like:
|
@Nasfame: I’m envisioning its being as simple as:
So As to performance: I don’t know Go internals well enough to speculate competently, but I would think the function call to be less performant than a slice literal. Of course, if |
Note that that suggested implementation means that a := []int{1, 2, 3}
b := slices.Of(a...)
a[0] = 4
fmt.Println(b[0]) will print |
I think that would be confusing. I would implement it as: func Of[T any](pieces ...T) []T {
return append([]T(nil), pieces...)
} and trust (or improve) the compiler to eliminate the intermediate argument slice when it isn't needed. [Edited to add the explicitly-typed |
I’m probably just missing something, but that seems to contradict the specification:
If |
@FGasper Read a few lines down.
|
Here’s a use case for this that I ran into just now:
Here, |
To sum up this proposal’s rationale: for the same reason why we all enjoy the freedom to write
… rather than
… it would be useful for Go to apply type inference to slice literals, e.g., This issue basically just formalizes that (I should note that the original |
In #47709 it was proposed to add type inference for slice literals, e.g.,
foo := []{"bar", "baz"}
. That proposal was declined in favour of creating an equivalent function inslices
.This issue proposes a
slices.Of(…)
method to do that, e.g.:… would be equivalent to:
The benefit is minimal in a trivial case like the above, but to create a slice of
*somepackage.NameThatIsRatherLong
it would be helpful.The text was updated successfully, but these errors were encountered: