Slices
are a built-in data type in Golang similar to arrays, except that a slice
has no specified length. All elements within a slice
must have the same type.
The code below shows how to declare a slice
literal with the string
type specification:
newSlice := []string{"a", "b", "c", "d"}
slice
contains an elementTo check if a particular element is present in a slice
object, we need to perform the following steps:
for
loop to iterate over each element in the slice
.==
) to check if the current element matches the element you want to find.The code below demonstrates this process.
package main import ( "fmt" ) func main(){ // initialize a slice literal newSlice := []string{"a", "b", "c", "d"} fmt.Println("The original slice is:", newSlice) // initialize the strings to search for searchString := "c" // initialize a found flag found := false // iterate over the slice for i, v := range newSlice { // check if the strings match if v == searchString { found = true fmt.Println("The slice contains", searchString, "at index", i) break } } // if string not found if found == false { fmt.Println("The slice does not contain", searchString) } }
In the code above:
In line , we import the fmt
package for printing.
In line , we initialize a slice literal of the string
type called newSlice
. At the time of declaration, newSlice
contains values.
Then, the code initializes the string to check the slice
for in line . We also declare a boolean
variable found
to serve as a flag that indicates whether or not the searchString
is present in newSlice
.
The for
loop in line proceeds to iterate over each value in newSlice
.
The if
statement in line checks if the current element matches searchString
. If both strings match, found
is set to true
. The code prints the index at which the element was found and the loop is terminated.
If the slice
does not contain searchString
, the loop finishes its execution. However, the value of found
would still be false
. Consequently, the if
statement in line checks whether or not the string was found.
RELATED TAGS
CONTRIBUTOR
View all Courses