How Can I Implement a Generic Comparison Operator in Go?

Patricia Arquette
Release: 2024-11-04 02:01:01
Original
264 people have browsed it

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
}
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!