You could write helpers:

func Left[A, B any](a A, b B) A { return a }
func Right[A, B any](a A, b B) B { return b }

Which you can then insert

useOne(Left(returnMany())
useOne(Right(returnMany())

But TBQH, I would not consider this good style. It ultimately adds more
noise and overhead, as people now have to figure out what Left and Right do
(you might argue that they should be named better, but still).

The right thing to do here, in my opinion, is to just accept the extra
statement. Yes, it's a little bit more noisy. But it's not a dramatic
enough different to justify deviating from what the core language gives you.

On Mon, Aug 29, 2022 at 10:43 AM Tanmay Das <tanmaymi...@gmail.com> wrote:

> Hi,
>
> I am relatively new to the Go language, and I have always wanted to ask
> this question:
>
> Consider the following snippet:
>
> package main
>
> import "fmt"
>
> func returnMany() (int, int) {
>     return 4, 2
> }
>
> func useOne(value int) {
>     fmt.Println(value)
> }
>
> func main() {
>     useOne(returnMany())
> }
>
> The returnMany function returns multiple values and the useOne function
> accepts only a single value. I have often come across situations where the
> returnMany() resides in my codebase and the useOne() comes from an external
> library.
>
> The code above obviously fails to build. Typically as a consumer of
> "useOne" package, I know which value it expects and I can either do this:
>
> value, _ := returnMany()
> useOne(value)
>
> Or, this, depending on my need:
>
> _, value := returnMany()
> useOne(value)
>
> This makes inlining function calls impossible and adds a little bit of
> noise to the codebase, IMO.
>
> Is there a way I can inline this without introducing a temp variable?
> Pseudocode example:
>
> useOne(returnMany()[1]) // 4
> useOne(returnMany()[2]) // 2
>
> https://go.dev/play/p/gxKsnRKUAFY
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/80fbcec2-0ee2-4cde-ac31-de495cb97c20n%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/80fbcec2-0ee2-4cde-ac31-de495cb97c20n%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAEkBMfEvVVrHjBH8RZ7QBrHjsiqXFzqSveKsZhd7of6ZxoWCjw%40mail.gmail.com.

Reply via email to