Skip to content

Proposal: Go2: Tuple type #32941

Closed
Closed
@maxekman

Description

@maxekman

I propose the addition of a new built-in type tuple and that functions should always returns a single value:

// Single return value of int.
func f() int {
  return 1
}

// Single return value of the tuple (int, error).
func g() (int, error) {
  return 1, errors.New("error")
}

Destruction of the new tuple type should be handled as before when returning multiple arguments, in addition to being able to store the tuple in a var with separate destruction:

// Destruct inline with call.
i, err := g()

// Destruct from tuple var.
r := g()
j, err2 := r

A naive idea for how defining a user tuple type could look:

type Pair tuple (int, int)

My proposal is inspired by the ideas and problems from this article about Monads in Go by @awalterschulze: https://awalterschulze.github.io/blog/post/monads-for-goprogrammers/

In the article he describes composing functions that return errors, for example (not from the article):

func f() (int, err) {
  return 1, nil
}

func g(x (int, err)) (int, err) {
  return x
}

// Returns 1 and nil from f().
val, err := g(f())

Having these additions to the language would allow for some interesting functional concepts to be implemented cleanly.

I have tried to look for earlier proposals without finding any, please correct me if it has been brought up before. Would love to hear your thoughts!

Thanks,
Max Ekman

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions