How Can I Compare Values of Different Types in Go?

Linda Hamilton
Release: 2024-11-04 01:34:03
Original
737 people have browsed it

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

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

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!

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!