Golang静态检查是否使用类型参数实现接口。

huangapple go评论64阅读模式
英文:

golang static check whether implement interface with type parameter

问题

没有类型参数,我们可以使用这种方式来检查类型是否实现了接口。

type R struct{}

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

var _ io.Reader = R{}

如何使用类型参数进行静态检查?
例如:

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)

如何在编译时检查*MyArray是否实现了SortArray接口?

英文:

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) =&gt;
	// -1 : a &lt; b
	//  0 : a == b
	//  1 : a &gt; 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?

答案1

得分: 0

你需要使用一个类型为XComparator来实例化*MyArray[X]

type testComparator struct {
   Comparator[testComparator]
}

var _ SortArray[testComparator] = &MyArray[testComparator]{}
英文:

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

type testComparator struct {
   Comparator[testComparator]
}

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

答案2

得分: 0

不需要定义一个实现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
}
英文:

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

type Comparator[T any] interface {
    // a.Compare(b) =&gt;
    // -1 : a &lt; b
    //  0 : a == b
    //  1 : a &gt; 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 &amp;arr
}

huangapple
  • 本文由 发表于 2022年8月20日 10:04:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/73423636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定