Go 1.18 generic tuples

Overview

go-tuple: Generic tuples for Go 1.18.

Go

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.

Features

Create tuples from function calls

func vals() (int, string) {
    return 5, "hi!"
}

func main() {
    tup := tuple.New2(vals())
    fmt.Println(tup.V1)
    fmt.Println(tup.V2)
}

Forward tuples as function arguments

func main() {
    tup := tuple.New2(5, "hi!")
    printValues(tup.Values())
}

func printValues(a int, b string) {
    fmt.Println(a)
    fmt.Println(b)
}

Access tuple values

tup := tuple.New2(5, "hi!")
a, b := tup.Values()

Formatting

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"}

Notes

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.

Contributing

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!

You might also like...
Package ethtool allows control of the Linux ethtool generic netlink interface.

ethtool Package ethtool allows control of the Linux ethtool generic netlink interface.

rconn is a multiplatform program for creating generic reverse connections. Lets you consume services that are behind firewall or NAT without opening ports or port-forwarding.
rconn is a multiplatform program for creating generic reverse connections. Lets you consume services that are behind firewall or NAT without opening ports or port-forwarding.

rconn (r[everse] conn[ection]) is a multiplatform program for creating reverse connections. It lets you consume services that are behind NAT and/or fi

Go library for decoding generic map values into native Go structures and vice versa.

mapstructure mapstructure is a Go library for decoding generic map values to structures and vice versa, while providing helpful error handling. This l

Generic Prometheus ⟷ MQTT Bridge

Promqtt: Prometheus ⟷ MQTT Bridge Promqtt makes Prometheus MQTT capable in a truly generic way. It has no assumptions on message payloads or topic lay

The k8s-generic-webhook is a library to simplify the implementation of webhooks for arbitrary customer resources (CR) in the operator-sdk or controller-runtime.

k8s-generic-webhook The k8s-generic-webhook is a library to simplify the implementation of webhooks for arbitrary customer resources (CR) in the opera

The first generic linked list in go :dancer:

linkedlist.go The first generic linked list in go 💃 gotip first of all you need to install the master version of golang. go install golang.org/dl/got

Optimistic rollup tech, minimal and generic.

Opti Optimistic rollup tech, minimal and generic. VERY experimental, just exploratory code, question is: 1:1 EVM rollup with interactive fraud proof p

Generic error handling with panic, recover, and defer.

Generic error handling with panic, recover, and defer.

conditiond is a generic constraint and policy evaluator.

conditiond conditiond is a generic constraint and policy evaluator. This tool lets you define constraints in data and evaluate them at run time. It's

Go datastructures for a generic world

Generic data structures for Go With the upcoming release of 1.18, it's now possible to build a library of generic data structures in Go. The purpose o

Generic impersonation and privilege escalation with Golang. Like GenericPotato both named pipes and HTTP are supported.

This is very similar to GenericPotato - I referenced it heavily while researching. Gotato starts a named pipe or web server and waits for input. Once

Generic mapStringInterface tool for extracting of data for CSV output

Generic mapStringInterface tool for extracting of data for CSV output

An experimental generic functional utility library inspired by Lodash

go-godash An experimental generic functional utility library inspired by Lodash Implemented functions Map Reduce Sum Filter Take TakeWhile Drop DropWh

Generic templating tool with support of JSON, YAML and TOML data

gotempl Small binary used to generate files from Go Templates and data files. The following formats are supported: JSON YAML TOML Usage usage: gotempl

generic sort for slices in golang

slices generic sort for slices in golang basic API func BinarySearch[E constraints.Ordered](list []E, x E) int func IsSorted[E constraints.Ordered](li

Generic slices for Go 1.8+

Slice A simple package that makes working with slices a little bit easier with the help of generics. Install go get github.com/twharmon/slice Example

Generic batches for go

batch import "github.com/ninedraft/batch" Package batch contains a generic batch buffer, which accumulates multiple items into one slice and pass it i

This package provides a generic way of deep copying Go objects

Package for copying Go values This package provides a generic way of deep copying Go objects. It is designed with performance in mind and is suitable

A slice backed binary heap with support for generic type parameters.

go-binaryheap A slice backed binary heap where the order can be customized by a comparison function. The main branch now requires go 1.18 because the

Comments
  • Cannot be used as channel payloads

    Cannot be used as channel payloads

    The documentation states that "Tuples can be used as slice or array items, map keys or values, and as channel payloads." However, attempting to use one results in a syntax error:

    tup := make(chan (int, float64))
    
    syntax error: unexpected comma, expecting )
    

    If tuples cannot be used as channel payloads please update the documentation to make a note of this, or if they can be used as channel payloads please include examples of how to do so.

    documentation 
    opened by altayhunter 2
  • Revert

    Revert "Add tests directory for tuple tests"

    Reverts barweiss/go-tuple#5

    I'm reverting this because Go coverage tools expect the test files to be in the same package as the tested files, otherwise coverage detection will be off.

    opened by barweiss 0
  • Add comparison feature

    Add comparison feature

    Implement comparison between two tuples of the same length with the same type parameters.

    Wanted syntax:

    tup1 := tuple.New2(1, "first")
    tup2 := tuple.New2(1, "second")
    
    switch tup1.Compare(tup2) {
        case tuple.LessThan:
            fmt.Printf("tup1 is less than tup2")
        case tuple.GreaterThan, tuple.Equal:
            fmt.Printf("tup1 is greater than or equal to tup2")
    }
    
    enhancement 
    opened by barweiss 0
Releases(v1.0.2)
  • v1.0.2(Mar 16, 2022)

  • v1.0.1(Jan 22, 2022)

  • v1.0.0(Jan 14, 2022)

    The first release of go-tuple.

    go-tuple follows semantic versioning. This means:

    • Incompatible API changes that are not backwards compatible will bump the "major" version, and reset the "minor" and "patch" versions.
    • New features that are backwards-compatible will bump the "minor" version and reset the "patch" version.
    • Bug fixes that are backwards-compatible will bump the "patch" version.

    Supported features:

    • Tuples can contain values of different types.
    • Support tuples with a varying number of values, from 1 to 9.
    • Tuples can be constructed with the New* function.
    • Tuples implement the Stringer and GoStringer interfaces.
    • Tuples of the same type can be compared and ordered.

    What's Changed

    • Fix GitHub action by @barweiss in https://github.com/barweiss/go-tuple/pull/1
    • Fix code snippets in README by @barweiss in https://github.com/barweiss/go-tuple/pull/2
    • Add tests directory for tuple tests by @barweiss in https://github.com/barweiss/go-tuple/pull/5
    • Change generated code to reuse type parameters constraint by @barweiss in https://github.com/barweiss/go-tuple/pull/7
    • Revert "Add tests directory for tuple tests" by @barweiss in https://github.com/barweiss/go-tuple/pull/8
    • Add initial support for tuple comparison by @barweiss in https://github.com/barweiss/go-tuple/pull/9
    • Add lint and coverage steps to the GitHub action by @barweiss in https://github.com/barweiss/go-tuple/pull/10

    New Contributors

    • @barweiss made their first contribution in https://github.com/barweiss/go-tuple/pull/1

    Full Changelog: https://github.com/barweiss/go-tuple/commits/v1.0.0

    Source code(tar.gz)
    Source code(zip)
Owner
Bar Weiss
Bar Weiss
Go-generic-unboxing - A quick ready to ship demo for go generic using the official example

Go generic This repo contain basic demo for installing and running go1.18beta1 v

Shenouda Fawzy 1 Feb 1, 2022
Generic - Golang generic example

泛型 场景 假设需要写一个列表总数计算的函数,根据不同数据类型,我们可能分别要写 SumInts(data []int),SumFloats(data []fl

h2O 0 Jan 27, 2022
This library implements the pub/sub pattern in a generic way. It uses Go's generic types to declare the type of the event.

observer This library implements the pub/sub pattern in a generic way. It uses Go's generic types to declare the type of the event. Usage go get githu

Leon Steinhäuser 6 Nov 16, 2022
gpool - a generic context-aware resizable goroutines pool to bound concurrency based on semaphore.

gpool - a generic context-aware resizable goroutines pool to bound concurrency. Installation $ go get github.com/sherifabdlnaby/gpool import "github.c

Sherif Abdel-Naby 86 Oct 31, 2022
A generic oplog/replication system for microservices

REST Operation Log OpLog is used as a real-time data synchronization layer between a producer and consumers. Basically, it's a generic database replic

Dailymotion 114 Oct 23, 2022
a generic object pool for golang

Go Commons Pool The Go Commons Pool is a generic object pool for Golang, direct rewrite from Apache Commons Pool. Features Support custom PooledObject

jolestar 1.1k Jan 5, 2023
Go library for decoding generic map values into native Go structures and vice versa.

mapstructure mapstructure is a Go library for decoding generic map values to structures and vice versa, while providing helpful error handling. This l

Mitchell Hashimoto 6.5k Jan 1, 2023
A generic fuzzing and delta-debugging framework

Tavor Tavor (Sindarin for woodpecker) is a framework for easily implementing and using fuzzing and delta-debugging. Its EBNF-like notation allows you

Markus Zimmermann 241 Dec 18, 2022
MongoDB generic REST server in Go

Mora - Mongo Rest API REST server for accessing MongoDB documents and meta data Documents When querying on collections those parameters are available:

Ernest Micklei 307 Dec 17, 2022
A better Generic Pool (sync.Pool)

This package is a thin wrapper over the Pool provided by the sync package. The Pool is an essential package to obtain maximum performance by reducing the number of memory allocations.

null 42 Dec 1, 2022