Home >Backend Development >Golang >How Can I Compare Values of Different Types in Go?
What is the Comparable Interface Called?
In Go, there is no explicit comparable interface. To compare values of different types, you can use the Less function.
Here's how you can implement a Less function:
func Less(a, b interface{}) bool { switch a.(type) { case int: if ai, ok := a.(int); ok { if bi, ok := b.(int); ok { return ai < bi } } case string: if ai, ok := a.(string); ok { if bi, ok := b.(string); ok { return ai < bi } } // ... default: panic("Unknown") } return false }
You can use the Less function to compare values in a linked list and insert new elements in a sorted manner:
func Insert(val interface{}, l *list.List) *list.Element { e := l.Front() if e == nil { return l.PushFront(val) } for ; e != nil; e = e.Next() { if Less(val, e.Value) { return l.InsertBefore(val, e) } } return l.PushBack(val) }
The above is the detailed content of How Can I Compare Values of Different Types in Go?. For more information, please follow other related articles on the PHP Chinese website!