DEV Community

Saleh Rahimzadeh
Saleh Rahimzadeh

Posted on

reflexive and non-reflexive keys in Go (Golang)

The terms "reflexive" and "non-reflexive" keys are not standard terminology.
However, based on the context, it seems you might be referring to how keys are used in maps or how they are compared for equality.

Reflexive Key

A reflexive key refers to a key that is equal to itself.
In Go, this is a fundamental property of equality.
For example, if you have a key k, the expression k == k should always evaluate to true.
This is a basic requirement for any key used in a map or for comparison operations.

type MyKey struct {
    ID int
}

k := MyKey{ID: 1}
fmt.Println(k == k) // true (reflexive)
Enter fullscreen mode Exit fullscreen mode

Non-Reflexive Key

A non-reflexive key would imply a key that is not equal to itself, which would violate the basic rules of equality in Go.
Such keys cannot be used in maps or for comparisons because Go requires keys to be reflexive, symmetric, and transitive for correct behavior.

Example of an invalid key (hypothetical, as this would break Go's rules):

// This is not valid Go code, as it violates the reflexive property.
type InvalidKey struct {
    ID int
}

func (k InvalidKey) Equal(other InvalidKey) bool {
    return k.ID != other.ID // Non-reflexive by design
}

k := InvalidKey{ID: 1}
fmt.Println(k.Equal(k)) // false (non-reflexive, invalid in Go)
Enter fullscreen mode Exit fullscreen mode

Key Requirements in Go Maps

In Go, keys used in maps must be comparable. This means:

  1. The key type must support the == and != operators.
  2. The equality comparison must be reflexive (k == k is always true), symmetric (k1 == k2 implies k2 == k1), and transitive (k1 == k2 and k2 == k3 implies k1 == k3).

Common types that can be used as keys in maps include:

  • Basic types (int, string, float64, etc.)
  • Structs (if all their fields are comparable)
  • Arrays (if their element types are comparable)

Types that cannot be used as keys include:

  • Slices
  • Maps
  • Functions
  • Structs with non-comparable fields (e.g., slices or maps)

Top comments (0)