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
DDDOriginal
2024-11-29 02:11:08978browse

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")
}

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}

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!

Statement:
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