Home  >  Article  >  Backend Development  >  How Can I Implement a Generic Comparison Operator in Go?

How Can I Implement a Generic Comparison Operator in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 02:01:01310browse

How Can I Implement a Generic Comparison Operator in Go?

What is the comparable interface called?

In Go, there is no predefined interface that provides a generic comparison operator (<). Instead, you can define your own Less function to compare your types. The Less function takes two arguments of the same type and returns a boolean indicating whether the first argument is less than the second.

Here's an example of a Less function that can compare integers and strings:

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 insert elements into a sorted linked list:

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)
}

This Insert function will maintain the linked list in sorted order based on the Less function.

The above is the detailed content of How Can I Implement a Generic Comparison Operator in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn