Home > Backend Development > Golang > How Can I Efficiently Check for Value Existence in a Go List?

How Can I Efficiently Check for Value Existence in a Go List?

DDD
Release: 2024-11-29 02:11:08
Original
868 people have browsed it

How Can I Efficiently Check for Value Existence in a Go List?

Checking Value Presence in a List in Go

In Python, the in keyword conveniently verifies if an element is present in a list. Go, on the other hand, lacks an explicit equivalent. This article explores techniques for implementing such a check in Go.

One approach involves using a set, which maps values to unused integer values. However, this requires an artificial integer specification for each element and isn't considered an ideal solution.

A more elegant approach is to leverage a map of strings to booleans. The map serves as a set, and the absence of a key-value pair in the map equates to false, which can be interpreted as the element not being in the list.

valid := map[string]bool{"red": true, "green": true, "yellow": true, "blue": true}

if valid[x] {
    fmt.Println("found")
} else {
    fmt.Println("not found")
}
Copy after login

Note:

For efficiency with large lists, consider either initializing the map using a for range loop or creating an untyped constant to optimize the boolean value assignment.

var t = true
valid := map[string]bool{"red": t, "green": t, "yellow": t, "blue": t}
Copy after login

The above is the detailed content of How Can I Efficiently Check for Value Existence in a Go List?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template