About struct fields in type parameters

112 views
Skip to first unread message

tapi...@gmail.com

unread,
Nov 12, 2021, 12:10:30 PM11/12/21
to golang-nuts

    // structField is a type constraint whose type set consists of some
    // struct types that all have a field named x.
    type structField interface {
        struct { a int; x int } |
            struct { b int; x float64 } |
            struct { c int; x uint64 }
    }

    // This function is INVALID.
    func IncrementX[T structField](p *T) {
        v := p.x // INVALID: type of p.x is not the same for all types in set
        v++
        p.x = v
    }

However, it still fails to compile if all the types of the x fields are identical.

    type structField interface {
        struct { a int; x int } |
            struct { b int; x int } |
            struct { c int; x int }
    }

    func IncrementX[T structField](p *T) {
        v := p.x // p.x undefined (type *T has no field or method x)
        v++
        p.x = v  // p.x undefined (type *T has no field or method x)
    }



tapi...@gmail.com

unread,
Nov 12, 2021, 12:13:13 PM11/12/21
to golang-nuts
And this fails to compile, although the docs says it is valid:

    // sliceOrMap is a type constraint for a slice or a map.
    type sliceOrMap interface {
        []int | map[int]int
    }

    // Entry returns the i'th entry in a slice or the value of a map
    // at key i. This is valid as the result of the operator is always int.
    func Entry[T sliceOrMap](c T, i int) int {
        // This is either a slice index operation or a map key lookup.
        // Either way, the index and result types are type int.
        return c[i] // invalid operation: cannot index c (variable of type T constrained by sliceOrMap
    }

tapi...@gmail.com

unread,
Nov 12, 2021, 12:17:33 PM11/12/21
to golang-nuts
The SliceConstraint example also doesn't work.

Is the doc I mentioned outdated?

Axel Wagner

unread,
Nov 12, 2021, 12:21:08 PM11/12/21
to tapi...@gmail.com, golang-nuts
Yes, the doc is outdated. Since then, several changes have been made to the design, to accomodate issues that either came up during the discussion or where discovered after - one of the more significant is https://github.com/golang/go/issues/45346, but there are others.
That's why I said we should probably wait for the actual spec changes before discussing it further, as there currently is no single authoritative source for what will land in go 1.18.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/785df174-2e12-49bc-a3af-f143a89cd831n%40googlegroups.com.

tapi...@gmail.com

unread,
Nov 12, 2021, 12:28:27 PM11/12/21
to golang-nuts
OK, I will try it several days later.
Reply all
Reply to author
Forward
0 new messages