Structural typing with generics [duplicate]
Asked Answered
D

0

0

I am trying to do structural typing with a generic type to implement an interface as shown

package main

type Queue[T comparable] struct {
    elements []T
}

type QueueOperations[T comparable] interface {
    Push(e T)
    Pop() T
    Len() int
}

var _ QueueOperations = (*Queue)(nil)

func main() {

}

I see I can't do that, as it is giving me a WrongTypeArgcount error "cannot use generic type QueueOperations[T comparable] without instantiation".

What is the right way to achieve this?

Dieselelectric answered 2/6, 2023 at 2:36 Comment(5)
You can do it like this: var _ QueueOperations[int] = (*Queue[int])(nil)Lemmie
@blackgreen This question is specially about checking generic interface implementation. Maybe it's worth keeping open?Lemmie
@ZekeLu I don't see how the solution would be appreciably different from those proposed in the links above. Or do you think we need an open question for each possible Go expression where a generic type could be used without instantiation? Feel free to cast your reopen vote.Boden
I agree that we don't need an open question for each possible case. When I'm looking into this question, I found something interesting and want to share it as an answer to this question. But it does not tie tightly to this question, so I'm OK to keep this one closed and create a new one to share what I have found. Thank you!Lemmie
@Boden Forget it. I just found that there is already a question about what I have found and is answered by you: #70381075. BTW, I just up voted the answer.Lemmie

© 2022 - 2024 — McMap. All rights reserved.