Operator not defined for T

trying to check if a given number is less than the other or not, so wrote the below:

package main

import "fmt"

type T interface {}

func Less(i, j T) bool {
	return i > j

But got the below error:

# command-line-arguments
.\hashmap.go:23:11: invalid operation: i > j (operator > not defined on interface)

How can I add such mathematical operations to general type element (number or string)?

From the Go Programming Language Specification:

The ordering operators < , <= , > , and >= apply to operands that are ordered .

Interface values are comparable.

Interfaces are not ordered.

Also, Go does not have generics. You need to write one implementation for each type.

I was able to do it with the help of type assertions, as below:

type T interface {

type hashMap struct {
	m map[T]T
	k []T

func (h *hashMap) Less(i, j int) bool {
	switch v := h.m[h.k[i]].(type) {
	case int:
		return v > h.m[h.k[j]].(int)
	case float32:
		return v > h.m[h.k[j]].(float32)
	case float64:
		return v > h.m[h.k[j]].(float64)
	case string:
		return v > h.m[h.k[j]].(string)
		return false

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.