Home > Software design >  golang static check whether implement interface with type parameter
golang static check whether implement interface with type parameter

Time:08-24

without type parameter, we can use this to check type whether impl interface.

type R struct{}

func (r R) Read([]byte) (int, error)

var _ io.Reader = R{}

how do this static check with type parameter ?
e.g

type Comparator[T any] interface {
    // a.Compare(b) =>
    // -1 : a < b
    //  0 : a == b
    //  1 : a > b
    Compare(t T) int
    Equal(t T) bool
}

type SortArray[E Comparator[E]] interface {
    BinarySearch(e E) (int, error)
}

type MyArray[E Comparator[E]] struct{
    inner []E
}

func (*MyArray[E]) BinarySearch(e E) (int, error)

how check whether *MyArray impl SortArray when compile time?

CodePudding user response:

You need to instantiate *MyArray[X] with a type X that is a Comparator.

type testComparator struct {
   Comparator[testComparator]
}

var _ SortArray[testComparator] = &MyArray[testComparator]{}

CodePudding user response:

no need to define a type which impl Comparator[T].

type Comparator[T any] interface {
    // a.Compare(b) =>
    // -1 : a < b
    //  0 : a == b
    //  1 : a > b
    Compare(t T) int
    Equal(t T) bool
}

type SortArray[E Comparator[E]] interface {
    BinarySearch(e E) (int, error)
}

type MyArray[E Comparator[E]] struct{
    inner []E
}

func (*MyArray[E]) BinarySearch(e E) (int, error){
    return 0, nil
}

func _[E Comparator[E]]() SortArray[E]{
    var arr MyArray[E]
    return &arr
}
  •  Tags:  
  • go
  • Related