Skip to content

Proposal: make generic code clearer #36177

Closed
@xushiwei

Description

@xushiwei

Refer: https://blog.golang.org/why-generics

My first question is how to define a generic type or function.

func New (type Node, Edge G) (nodes []Node) *Graph(Node, Edge) {
    ...
}

I think this code is terrible. Go's function prototype is more complex than other languages.

Generics make it more terrible.

Maybe the following code is clearer.

[Node, Edge G]
func New(nodes []Node) *Graph[Node, Edge] {
    ...
}

My second question is how to define a contract.

contract Ordered(T) {
    T int, int8, int16, int32, int64,
        uint, uint8, uint16, uint32, uint64, uintptr,
        float32, float64,
        string
}

Maybe the following code is clearer.

contract Ordered(T) {
    (T) < (T) bool
}

The following is a completed example.

package example

// --------------------------------------------------------------------------

contract builtinLesser(T) {
    (T) < (T) bool
}

[T builtinLesser]
func Less(a, b T) bool {
    return a < b
}

contract lesser(T) {
    (T) Less(T) bool
} 

[T lesser]
func Less(a, b T) bool {
    return a.Less(b)
}

contract Lessable(T) {
    Less(a, b T) bool
}

// --------------------------------------------------------------------------

[T Lessable]
func Min(a ...T) T {
    v := a[0]
    for i := 1; i < len(a); i++ {
        if Less(a[i], v) {
            v = a[i]
        }
    }
    return v
}

[T Lessable]
func Min(a, b T) T { // Specialization
    if Less(a, b) {
        return a
    }
    return b
}

// --------------------------------------------------------------------------

contract G(Node, Edge) {
    (Node) Edges() []Edge
    (Edge) Nodes() (from Node, to Node)
}

[Node, Edge G]
type Graph struct {
    // ...
}

[Node, Edge G]
func New(nodes []Node) *Graph[Node, Edge] {
    ...
}

// --------------------------------------------------------------------------

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeLanguageChangeSuggested changes to the Go languageProposalgenericsIssue is related to genericsv2An incompatible library change

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions