Golang generics with custom type result in error

Viewed 14

The following code

package main

import "fmt"

type Name1 struct {
    First string
}

type Name2 struct {
    First string
}

type Name interface {
    Name1 | Name2
}

func main() {
    n1a := Name1{First: "test"}
    n1b := Name1{First: "test"}
    fmt.Printf("n1a == n1b: %v", isEqual(n1a, n1b))

    n2a := Name2{First: "test"}
    n2b := Name2{First: "test"}
    fmt.Printf("n2a == n2b: %v", isEqual(n2a, n2b))
}

func isEqual[T Name](l, r T) bool {
    if l.First != r.First {
        return false
    }
    return true
}

has compilation errors

./prog.go:30:7: l.First undefined (type T has no field or method First)
./prog.go:30:18: r.First undefined (type T has no field or method First)

Go playground: https://go.dev/play/p/Wa0jUIGTQEg

Changing [T Name] to [T any] still result in same errors.

Does golang support generics with custom types? or does it only work with primitive types?

0 Answers
Related