Go 1.18+ generic tuple
Go 1.18+ tuple implementation.
Use tuples to store 1 or more values without needing to write a custom struct.
tup := tuple.New2(5, "hi!")
fmt.Println(tup.V1) // Outputs 5.
fmt.Println(tup.V2) // Outputs "hi!".Tuples come in various sizes, from 1 to 9 elements.
longerTuple := tuple.New5("this", "is", "one", "long", "tuple")Tuples can be used as slice or array items, map keys or values, and as channel payloads:
// Map holding tuples.
tupInMap := make(map[tuple.T2[string, string]]Person)
tupInMap[tuple.New2("John", "Doe")] = Person{
FirstName: "John",
LastName: "Doe",
// ...
}
// Channel holding tuples.
tupInChan := make(chan tuple.T2[string, error])
go func() {
defer close(tupInChan)
tupInChan guest.name {
return 1
}
return 0
}
func main() {
tup1 := tuple.New2(person{name: "foo", age: 20}, person{name: "bar", age: 24})
tup2 := tuple.New2(person{name: "bar", age: 20}, person{name: "baz", age: 24})
fmt.Println(tuple.LessThan2C(tup1, tup2)) // true.
}In order to call the complex types variation of the comparable functions, all tuple types must match the Comparable constraint.
While this is not ideal, this a known inconvenience given the current type parameters capabilities in Go. Some solutions have been porposed for this issue (lesser, for example, beatifully articulates the issue), but they still demand features that are not yet implemented by the language.
Once the language will introduce more convenient ways for generic comparisons, this package will adopt it.
Tuples implement the Stringer and GoStringer interfaces.
fmt.Printf("%s\n", tuple.New2("hello", "world"))
// Output:
// ["hello" "world"]
fmt.Printf("%#v\n", tuple.New2("hello", "world"))
// Output:
// tuple.T2[string, string]{V1: "hello", V2: "world"}The tuple code and test code are generated by the scripts/gen/main.go script.
Generation works by reading tuple.tpl and tuple_test.tpl using Go's text/template engine.
tuple.tpl and tuple_test.tpl contain the templated content of a generic tuple class, with variable number of elements.
Please feel free to contribute to this project by opening issues or creating pull-requests. However, keep in mind that generic type features for Go are still in their early stages, so there might not be support from the language to your requested feature.
Also keep in mind when contributing to keep the compilation time and performance of this package fast.
Feel free to contact me at [email protected] for questions or suggestions!
No open issues yet, or sync has not completed.