“Голанг проверьте, если в массиве” Ответ

Голанг проверьте, если в массиве

func stringInSlice(a string, list []string) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}
WizardX11

Проверьте, существует ли элемент в массиве Golang

Mostafa has already pointed out that such a method is trivial to write, and mkb gave you a hint to use the binary search from the sort package. But if you are going to do a lot of such contains checks, you might also consider using a map instead.

It's trivial to check if a specific map key exists by using the value, ok := yourmap[key] idiom. Since you aren't interested in the value, you might also create a map[string]struct{} for example. Using an empty struct{} here has the advantage that it doesn't require any additional space and Go's internal map type is optimized for that kind of values. Therefore, map[string] struct{} is a popular choice for sets in the Go world.
Santino

Ответы похожие на “Голанг проверьте, если в массиве”

Вопросы похожие на “Голанг проверьте, если в массиве”

Больше похожих ответов на “Голанг проверьте, если в массиве” по Go

Смотреть популярные ответы по языку

Смотреть другие языки программирования