You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
proposal: spec: allow conversion between return types and structs #33080
The goal of this proposal is to allow easy conversion from a function return to a struct with the same field types and order.
This would allow to more easily pass a function result to a channel, without having to manually create temporary variables and filing them up in a struct before it is sent thorough a channel.
type T struct {
i string,
i2 int,
}
type T2 tuple (string,int)
func A() (string,int) {...}
And in another function:
func main() {
var a T
var b T2
a = A() //valid, with this proposal
b = A() //valid, with another proposal
d,c := A() //valid, currently
}
Another proposal is: #32941
We can add the tuple type, all this conversions, return type will still be multiple return,but tuple will be constructed in place, then converted to the struct(or just saved).
However this is related features, i don't see any valuable benefits of adding these features aside.
There is an interesting duality for function arguments: today it is possible to pass the results of a multi-result function directly to another function that accepts the same argument list (https://play.golang.org/p/f3kNTppbVMc).
Should it be possible to make such a call by unpacking a struct?
If so, arguably that should require explicit syntax — what would it look like?
There is an interesting duality for function arguments: today it is possible to pass the results of a multi-result function directly to another function that accepts the same argument list (https://play.golang.org/p/f3kNTppbVMc).
Should it be possible to make such a call by unpacking a struct?
If so, arguably that should require explicit syntax — what would it look like?
Technically, yes, but I don't think that it's good idea. Readability will be almost lost(due to required declaration reading).
This proposal does not discuss assignability, only convertibility. The example @tema3210 would actually be invalid, as the proposal currently stands.
That being said, I don't see anything preventing a future discussion on assignability. Nevertheless, as for a hypothetical expansion syntax, why not just use ... ?
s:=struct{_int; _int; _string}{1, 2, "foo"}
x, y, z:=s...
Reacted by Jeremy Faller, Oleg Kovalov, Beoran, Álvaro López Espinosa, Akhil Indurti, Komu Wairagu, Marcelo Pires, jimmyfrasche, yiyus, Brandon Bennett and 1 more
But then you have issues of naming the struct fields. If you converted an interface method call into a struct, you'd need to use the name of the interface method's named return values (which often aren't named, or are named all lowercase, so the struct field would have unexported fields).
Suppose that instead of Pair(F()) we change the rules of composite literals so that a function call with multiple results can be used, and treated as though the results appeared in the composite literal as separate values.
That is, in the original example, instead of
gofunc() { c<-Pair(F()) }()
we permit
gofunc( { c<-Pair{F()} }()
This would be permitted for slice/array composite literals as well. (It wouldn't work for maps as there would be no way to specify both the key and the value.)
This seems like a relatively simple extension to the way that functions with multiple results can be used today.
Reacted by jimmyfrasche, lucy, Dmitriy Matrenichev, Laurent Moussault, Viktor Kojouharov, Bryan C. Mills, Michal Bohuslávek, qaisjp, Yassir Hassan, Phil and 1 more
@egonelbre Of course this is an option. But I think the point the proposal author is trying to make is that this extra work shouldn't be required: "The goal of this proposal is to allow easy conversion from a function return to a struct with the same field types and order." (#33080 (comment))
Reacted by Egon Elbre, Viktor Kojouharov, Dmitriy Matrenichev, Oleg Kovalov, Yassir Hassan and anvesh9652
Regarding #33080 (comment), to clarify: Like for function invocations f(g() where g returns multiple results and f accepts multiple results, if S is a composite literal type (struct, array, or slice) we would only allow S{g()} and not S{a, b, g(), c, d} or S{g(), g()}.
Would this change make Go easier or harder to learn, and why?
It won't influence the learning curve
Adding anything to the language means there's more to learn. Maybe new users won't write that code initially, but they'll eventually want to read & understand other people's code that uses such new features.
Would this change make Go easier or harder to learn, and why?
It won't influence the learning curve
Adding anything to the language means there's more to learn. Maybe new users won't write that code initially, but they'll eventually want to read & understand other people's code that uses such new features.
My understanding of that question is that since this builds on an existing feature, it won't make learning Go harder. It adds more, but doesn't make things harder to learn, a new user, knowing that you can convert between types, will know what the new code does without knowing the new rule. Though it might be possible I've misunderstood the question.
This is essentially @bradfitz's #33080 (comment) but split into two parts and with a solution for field naming:
Introduce a new way for writing struct types without specifying field names. In struct (int, string), each field is automatically named Fn where n is its position in the definition. So struct (int, string) is 100% sugar for/completely identical to
struct {
F0intF1string
}
This variant of struct declaration is a tuple type without introducing a new kind of type, just a convention and a shorthand. More important here, it gives a way to talk about structs with unspecified field names.
Introduce a new builtin tuple. It creates and populates a struct without specified field names based on its arguments: tuple(false, 3.14) has type struct (bool, float64).
Because it's a function, the usual rules apply so, for func f() (T, error), tuple(f()) has type struct (T, error).
With those and ... for struct unpacking, you can write:
There's another language improvement that would help out this use case a little bit. Rust, TypeScript, Haskell, and other languages allow for specifying just the field name and then automatically using an in scope variable with the same name as the value. So a snipped from the example would become:
count, id:=F()
c<-Pair{count, id}
Not a huge improvement for this example, but when these patterns are allowed for both structuring and de-structuring it can add up in a program in a lot of places like this and the nice thing is it doesn't negatively affect readability.
changed the title [-]Proposal: allow conversion between return types and structs[/-][+]proposal: allow conversion between return types and structs[/+]on Sep 16, 2022
changed the title [-]proposal: allow conversion between return types and structs[/-][+]proposal: Go 2: allow conversion between return types and structs[/+]on Sep 16, 2022
As far as I can tell from a first reading, none of the suggestions here consider backwards compatibility.
In the current language, it is always backwards-compatible to add a comparable field to a struct, in the sense that all existing code will continue to compile. There are two exceptions to this:
Untagged struct literals. These are explicitly exempted by the Go 1 compatibility promise. There is also a vet check for them, so people generally don't use them. It's always easy to switch to tagged literals.
If the struct has only exported fields, clients can define their own identical struct type and convert between the two. But nobody ever does this, because why would you?
Some proposals here change the calculus. The one that lets you write a struct conversion that takes multiple return values will make struct conversion much more common, so if your package defines
type S struct { Int int; Err error }
you won't be able to add a field to that because clients might be using it to convert calls to strconv.Atoi.
The proposal for S{F()} puts untagged literals back in play, in a way where there is no easy rewrite to a tagged form.
Allowing f(s...) where s is a struct has the same issue.
Any syntax that takes all struct fields together and translates them to another form—args, return values, whatever—will affect backwards compatibility.
changed the title [-]proposal: Go 2: allow conversion between return types and structs[/-][+]proposal: spec: allow conversion between return types and structs[/+]on Aug 6, 2024
Activity
tema3210 commentedon Jul 12, 2019
As example we can have:
And in another function:
Another proposal is: #32941
We can add the tuple type, all this conversions, return type will still be multiple return,but tuple will be constructed in place, then converted to the struct(or just saved).
However this is related features, i don't see any valuable benefits of adding these features aside.
bcmills commentedon Jul 12, 2019
There is an interesting duality for function arguments: today it is possible to pass the results of a multi-result function directly to another function that accepts the same argument list (https://play.golang.org/p/f3kNTppbVMc).
Should it be possible to make such a call by unpacking a struct?
If so, arguably that should require explicit syntax — what would it look like?
tema3210 commentedon Jul 12, 2019
Technically, yes, but I don't think that it's good idea. Readability will be almost lost(due to required declaration reading).
Personally I can't imagine syntax.
urandom commentedon Jul 12, 2019
This proposal does not discuss assignability, only convertibility. The example @tema3210 would actually be invalid, as the proposal currently stands.
That being said, I don't see anything preventing a future discussion on assignability. Nevertheless, as for a hypothetical expansion syntax, why not just use
...?bradfitz commentedon Sep 24, 2019
I was proposing to @griesemer that maybe we also use
...to unpack a struct in a call:Or even:
bradfitz commentedon Sep 24, 2019
And maybe using
struct(...)to convert an arbitrary function call return (or literals too?) into an unnamed struct:But then you have issues of naming the struct fields. If you converted an interface method call into a struct, you'd need to use the name of the interface method's named return values (which often aren't named, or are named all lowercase, so the struct field would have unexported fields).
(Braindump from me + @griesemer)
ianlancetaylor commentedon Oct 8, 2019
Suppose that instead of
Pair(F())we change the rules of composite literals so that a function call with multiple results can be used, and treated as though the results appeared in the composite literal as separate values.That is, in the original example, instead of
we permit
This would be permitted for slice/array composite literals as well. (It wouldn't work for maps as there would be no way to specify both the key and the value.)
This seems like a relatively simple extension to the way that functions with multiple results can be used today.
egonelbre commentedon Oct 9, 2019
Any reason not use:
griesemer commentedon Oct 9, 2019
@egonelbre Of course this is an option. But I think the point the proposal author is trying to make is that this extra work shouldn't be required: "The goal of this proposal is to allow easy conversion from a function return to a struct with the same field types and order." (#33080 (comment))
griesemer commentedon Oct 9, 2019
Regarding #33080 (comment), to clarify: Like for function invocations
f(g()wheregreturns multiple results andfaccepts multiple results, ifSis a composite literal type (struct, array, or slice) we would only allowS{g()}and notS{a, b, g(), c, d}orS{g(), g()}.rodcorsi commentedon Oct 15, 2019
Why not specify the struct field that function assigns:
4 remaining items
urandom commentedon Jan 22, 2020
@gopherbot please remove label WaitingForInfo
bradfitz commentedon Jan 22, 2020
Adding anything to the language means there's more to learn. Maybe new users won't write that code initially, but they'll eventually want to read & understand other people's code that uses such new features.
urandom commentedon Jan 23, 2020
My understanding of that question is that since this builds on an existing feature, it won't make learning Go harder. It adds more, but doesn't make things harder to learn, a new user, knowing that you can convert between types, will know what the new code does without knowing the new rule. Though it might be possible I've misunderstood the question.
jimmyfrasche commentedon Apr 12, 2020
This is essentially @bradfitz's #33080 (comment) but split into two parts and with a solution for field naming:
Introduce a new way for writing struct types without specifying field names. In
struct (int, string), each field is automatically named Fn where n is its position in the definition. Sostruct (int, string)is 100% sugar for/completely identical toThis variant of struct declaration is a tuple type without introducing a new kind of type, just a convention and a shorthand. More important here, it gives a way to talk about structs with unspecified field names.
Introduce a new builtin
tuple. It creates and populates a struct without specified field names based on its arguments:tuple(false, 3.14)has typestruct (bool, float64).Because it's a function, the usual rules apply so, for
func f() (T, error),tuple(f())has typestruct (T, error).With those and
...for struct unpacking, you can write:jimmyfrasche commentedon May 2, 2020
This could also be solved by generics.
This can be easily generated from 2 to some n large enough for most reasonable cases.
With that the previous code example is
That's almost as good as native syntax. It's more verbose and the arity gets brought up a lot, which is annoying but probably fine.
The only language change required is generics but
...for structs would obviate the Unpack method and allowaStructType{aTupleValue...}.gregwebs commentedon Sep 16, 2022
There's another language improvement that would help out this use case a little bit. Rust, TypeScript, Haskell, and other languages allow for specifying just the field name and then automatically using an in scope variable with the same name as the value. So a snipped from the example would become:
Not a huge improvement for this example, but when these patterns are allowed for both structuring and de-structuring it can add up in a program in a lot of places like this and the nice thing is it doesn't negatively affect readability.
jimmyfrasche commentedon Sep 16, 2022
For that to work there'd need to be some way to disambiguate it from sequentially filling the fields. In some other thread I used
Pair{:count, :id}.[-]Proposal: allow conversion between return types and structs[/-][+]proposal: allow conversion between return types and structs[/+][-]proposal: allow conversion between return types and structs[/-][+]proposal: Go 2: allow conversion between return types and structs[/+]jba commentedon Sep 8, 2023
As far as I can tell from a first reading, none of the suggestions here consider backwards compatibility.
In the current language, it is always backwards-compatible to add a comparable field to a struct, in the sense that all existing code will continue to compile. There are two exceptions to this:
Untagged struct literals. These are explicitly exempted by the Go 1 compatibility promise. There is also a vet check for them, so people generally don't use them. It's always easy to switch to tagged literals.
If the struct has only exported fields, clients can define their own identical struct type and convert between the two. But nobody ever does this, because why would you?
Some proposals here change the calculus. The one that lets you write a struct conversion that takes multiple return values will make struct conversion much more common, so if your package defines
you won't be able to add a field to that because clients might be using it to convert calls to
strconv.Atoi.The proposal for
S{F()}puts untagged literals back in play, in a way where there is no easy rewrite to a tagged form.Allowing
f(s...)wheresis a struct has the same issue.Any syntax that takes all struct fields together and translates them to another form—args, return values, whatever—will affect backwards compatibility.
griesemer commentedon Dec 8, 2023
I believe we should seriously consider the ideas suggested here. I filed #64613 which is a restatement of the best ideas in this proposal.
[-]proposal: Go 2: allow conversion between return types and structs[/-][+]proposal: spec: allow conversion between return types and structs[/+]