Consider the following code which just prints all the ENV vars
package main
import (
"fmt"
"os"
)
func main() {
for i, env := range os.Environ() {
fmt.Println(i, env)
}
}
Here, os.Environ() is supposed to return array of strings([] string), to loop over it. I need to to use range keyword & also for loop. Question is:
[]string
is already an array & we can iterate over arrays right?range
do? and what does for
loop does?Sorry if this question is too stupid, I am just starting with Go
As mentioned in Range Clauses:
A range clause provides a way to iterate over a array, slice, string, map, or channel.
If you want to iterate over an []string
, you need range
.
A For statement doesn't always use range.
ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
You have:
In its simplest form, a "
for
" statement specifies the repeated execution of a block as long as a boolean condition evaluates to trueA "for" statement with a
ForClause
is also controlled by its condition, but additionally it may specify an init and a post statement, such as an assignment, an increment or decrement statementA "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables if present and then executes the block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With