Home > Backend Development > Golang > How Can I Check if Three Values are Equal in Go?

How Can I Check if Three Values are Equal in Go?

Linda Hamilton
Release: 2024-11-04 03:57:01
Original
552 people have browsed it

How Can I Check if Three Values are Equal in Go?

Checking Equality of Three Values Elegantly

While the traditional approach with if a == b == c results in a syntax error, there are alternative methods to determine whether three values are equal.

Using a Clear and Concise Approach

The simplest solution remains:

<code class="go">if a == b && a == c {
    fmt.Println("All 3 are equal")
}</code>
Copy after login

This solution is straightforward and efficient, making comparisons on a per-pair basis.

Exploring Creative Solutions

Using a Map as a Set:

The len() function returns the number of unique keys in a map. By using a map with interface{} keys, we can check if all values are equal by comparing the map length to 1:

<code class="go">if len(map[interface{}]int{a: 0, b: 0, c: 0}) == 1 {
    fmt.Println("All 3 are equal")
}</code>
Copy after login

With Arrays:

Arrays are comparable, allowing us to compare multiple elements at once:

<code class="go">if [2]interface{}{a, b} == [2]interface{}{b, c} {
    fmt.Println("All 3 are equal")
}</code>
Copy after login

Using a Tricky Map:

We can index a map with a key that results in the comparison value:

<code class="go">if map[interface{}]bool{a: b == c}[b] {
    fmt.Println("All 3 are equal")
}</code>
Copy after login

With Anonymous Structs:

Structs are also comparable, so we can create an anonymous struct with the values and compare them:

<code class="go">if struct{ a, b interface{} }{a, b} == struct{ a, b interface{} }{b, c} {
    fmt.Println("All 3 are equal")
}</code>
Copy after login

With Slices:

To compare slices, we utilize the reflect.DeepEqual() function:

<code class="go">if reflect.DeepEqual([]interface{}{a, b}, []interface{}{b, c}) {
    fmt.Println("All 3 are equal")
}</code>
Copy after login

Using a Helper Function:

We can define a helper function to handle any number of values:

<code class="go">func AllEquals(v ...interface{}) bool {
    if len(v) > 1 {
        a := v[0]
        for _, s := range v {
            if a != s {
                return false
            }
        }
    }
    return true
}</code>
Copy after login

The above is the detailed content of How Can I Check if Three Values are Equal 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