Reputation: 1228
I am declcaring an interface in go
type comparable interface {
GetKey() float32
Compare(comparable) int
}
and implementing this interface by creating this structure
type Note struct {
id int
text string
priority float32
}
func (note Note) GetKey() float32 {
return note.priority
}
func (note Note) Compare(note2 Note) int {
if note.priority < note2.priority {
return -1
} else if note.priority > note2.priority {
return 1
} else {
return 0
}
}
But when I am passing note object into a function which accepts comparable interface as a parameter I am getting "Wrong type for method compare" error.
Am I missing something or doing something wrong? Please help
Thanks in advance
Upvotes: 1
Views: 335
Reputation: 18410
You are not implementing comparable
since you use Note
in compare method not comparable
. Compare(note2 Note)
is not same as Compare(comparable)
.
Use comparable
in Compare method to implement comaprable
interface
func (note Note) Compare(note2 comparable) int {
if note.GetKey()< note2.GetKey() {
return -1
} else if note.GetKey()> note2.GetKey() {
return 1
} else {
return 0
}
}
Upvotes: 3
Reputation: 273376
You declared comparable
as having a method with signature Compare(comparable) int
.
So func (note Note) Compare(note2 Note)
ought to be func (note Note) Compare(note2 comparable)
, to match the interface.
Otherwise, you're not implementing the same interface. To implement comparable
, your Compare
method needs to take any comparable
, but the one you declared for Note
takes only Note
, and not any comparable. It's a different method.
Here's a modified-to-work, minimal example based on your code: https://play.golang.org/p/ajH1s5gbGcQ
Upvotes: 3