golang slice check if element exists

(*-*)浩
Release: 2019-12-17 11:18:19
Original
3845 people have browsed it

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"}
Copy after login

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

func make([]T, len, cap) []T
Copy after login

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}
Copy after login

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)
Copy after login

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

len(s) == 5
cap(s) == 5
Copy after login

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!

Related labels:
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