Home  >  Article  >  Backend Development  >  golang slice check if element exists

golang slice check if element exists

(*-*)浩
(*-*)浩Original
2019-12-17 11:18:193767browse

golang slice check if element exists

Go's Slice type provides a convenient and effective way to process typed data sequences.

Slice is similar to an array in other languages, but has some unusual properties. (Recommended learning: go)

Slices

Arrays have their place, but they are a bit inflexible, so you won't find them in Go code They are often seen in . However, Slice is everywhere. They are array-based and provide powerful functionality and convenience.

The type specification of Slice is [] T, where T is the type of Slice element. Unlike array types, Slice types do not have a specified length.

A Slice literal is declared just like an array literal, except the number of elements is omitted:

letters := []string{"a", "b", "c", "d"}

Slices can be created using a built-in function called make, which has the following definition,

func make([]T, len, cap) []T

Where T represents the element type of the slice to be created. The make function takes a type, length and optional capacity. When called, make allocates an array and returns a slice referencing the array.

var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}

When the capacity parameter is omitted, it defaults to the specified length. Here's a more concise version of the same code:

s := make([]byte, 5)

The length and capacity of a slice can be checked using the built-in len and cap functions.

len(s) == 5
cap(s) == 5

The above is the detailed content of golang slice check if element exists. 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