Home > Backend Development > Golang > Trying to compare two values ​​of type V with Go generics doesn't work

Trying to compare two values ​​of type V with Go generics doesn't work

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2024-02-09 12:39:09
forward
585 people have browsed it

尝试比较 V 类型的两个值与 Go 泛型不起作用

php Editor Apple found that in Go language, two values ​​of type V cannot be directly compared when using generics. This means that comparisons cannot be made simply using == or != as you can with strings or integers. This is because generics are implemented differently and cannot directly compare values. In this case, we need to use a custom comparison function or method to perform the comparison operation to achieve the functionality we require. This is a detail to pay attention to, especially when writing code involving generics.

Question content

go version: go1.21rc2

I'm writing a function in go using generics that takes a value and returns true/false if the value is in a map.

In version 1 below, I don't understand why two values ​​cannot be compared when their type is any? But after converting to any in version 2, it works now... I guess I'm missing something obvious, but I don't quite understand it.

Version 1 (not working):

func invalues[m ~map[k]v, k comparable, v any](m m, v v) bool {
    for _, x := range maps.values(m) {
        if x == v {
            return true
        }
    }
    return false
}
Copy after login

Version 2 (Working):

func InValues[M ~map[K]V, K comparable, V any](m M, v V) bool {
    for _, x := range maps.Values(m) {
        if any(x) == any(v) {
            return true
        }
    }
    return false
}
Copy after login

Solution

V needs to be comparable to allow ==.
Converting to any then compares effectively because it uses non-generic == between any, which is always allowed.

The above is the detailed content of Trying to compare two values ​​of type V with Go generics doesn't work. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template