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
Hello Gophers,
We propose the implementation of a tuple type in Golang, which allows for the creation of a collection of elements of different types. The tuple type provides several advantages, including the ability to store and retrieve heterogeneous data, iterate over its elements, and obtain the type information of each element.
An example of the tuple type:
package main
import (
"fmt"
"reflect"
)
type tuple struct {
elements []any
}
type tupleElement struct {
elemindex int
elemvalue any
elemtype reflect.Type
}
func Tuple(elements ...any) *tuple {
return &tuple{elements: elements}
}
func (t *tuple) len() int {
return len(t.elements)
}
func (t *tuple) get(index int) (any, reflect.Type) {
if index < 0 || index >= len(t.elements) {
panic("index out of range")
}
return t.elements[index], reflect.TypeOf(t.elements[index])
}
func (t *tuple) valueAt(index int) any {
value, _ := t.get(index)
return value
}
func (t *tuple) typeAt(index int) reflect.Type {
_, typ := t.get(index)
return typ
}
func (t *tuple) Iterate() <-chan tupleElement {
ch := make(chan tupleElement)
go func() {
for i, elem := range t.elements {
ch <- tupleElement{i, elem, reflect.TypeOf(elem)}
}
close(ch)
}()
return ch
}
func (t *tuple) String() string {
result := "tuple{"
for i, elem := range t.elements {
result += fmt.Sprintf("%v (type: %s)", elem, reflect.TypeOf(elem))
if i < len(t.elements)-1 {
result += ", "
}
}
result += "}"
return result
}
// //////////////////////////////////////////////Example////////////////////////////////////////////////////////////////
func main() {
t := Tuple("Alice", 30, "Engineer", true, 42.0, struct { a int ; b string }{ 4 , "hello" } )
fmt.Printf("t[0] = %v (type: %s)\n", t.valueAt(0), t.typeAt(0))
fmt.Printf("t[1] = %v (type: %s)\n", t.valueAt(1), t.typeAt(1))
for elem := range t.Iterate() {
fmt.Printf("t[%d] = %v (type: %s)\n", elem.elemindex, elem.elemvalue, elem.elemtype)
}
fmt.Println(t)
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
The text was updated successfully, but these errors were encountered:
Proposal Details
Hello Gophers,
We propose the implementation of a tuple type in Golang, which allows for the creation of a collection of elements of different types. The tuple type provides several advantages, including the ability to store and retrieve heterogeneous data, iterate over its elements, and obtain the type information of each element.
An example of the tuple type:
The text was updated successfully, but these errors were encountered: