go by example for loop with range
In Go, range is used to iterate over data types and return corresponding values: 1. For slices and arrays, range returns indexes and element copies; 2. Unwanted indexes or values can be ignored using _; 3. For maps, range returns keys and values, but the iteration order is not fixed; 4. For strings, range returns rune indexes and characters (rune type), supporting Unicode; 5. For channels, range continues to read values until the channel is closed, and only a single element is returned. Using range can avoid manually managing indexes, making iteratives simpler and safer.
In Go, the for
loop combined with the range
keyword is commonly used to iterate over arrays, slices, strings, maps, and channels. Here's a clear example for each major use case.

1. Looping over a slice with range
package main import "fmt" func main() { fruits := []string{"apple", "banana", "cherry"} for index, value := range fruits { fmt.Printf("Index: %d, Value: %s\n", index, value) } }
Output:
Index: 0, Value: apple Index: 1, Value: banana Index: 2, Value: cherry
range
returns two values: the index and a copy of the element at that index.
2. Ignoring the index or value
If you don't need the index:
for _, value := range fruits { fmt.Println("Fruit:", value) }
If you only need the index:

for index := range fruits { fmt.Println("Index:", index) }
Use
_
to ignore values you don't need.
3. Looping over a map
ages := map[string]int{ "Alice": 25, "Bob": 30, "Charlie": 35, } for key, value := range ages { fmt.Printf("Name: %s, Age: %d\n", key, value) }
Map iteration order is not guaranteed — it's randomized in Go.
4. Looping over a string
s := "Go" for index, char := range s { fmt.Printf("Index: %d, Character: %c\n", index, char) }
Output:
Index: 0, Character: G Index: 1, Character: o
Note:
char
is arune
(Unicode code point), not a byte, which matters for multi-byte characters like "Hello World".
5. Looping over an array
numbers := [3]int{10, 20, 30} for i, v := range numbers { fmt.Printf("Position %d: %d\n", i, v) }
Same behavior as slices.
Summary of range
behaviors:
Data Type | First value | Second value |
---|---|---|
Slice / Array | Index (int) | Element (copy) |
String | Rune index (int) | Rune (rune type) |
Map | Key | Value |
Channel | N/A (only one value: element) | — |
For channels,
range
reads values until the channel is closed.
Example with channel:
ch := make(chan int, 2) ch <- 1 ch <- 2 close(ch) for value := range ch { fmt.Println("Received:", value) }
Basically, range
makes iteration clean and safe — no manual index management needed. Just remember to use _
when you don't need a value, and know what range
returns for each type.
The above is the detailed content of go by example for loop with range. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Use fmt.Scanf to read formatted input, suitable for simple structured data, but the string is cut off when encountering spaces; 2. It is recommended to use bufio.Scanner to read line by line, supports multi-line input, EOF detection and pipeline input, and can handle scanning errors; 3. Use io.ReadAll(os.Stdin) to read all inputs at once, suitable for processing large block data or file streams; 4. Real-time key response requires third-party libraries such as golang.org/x/term, and bufio is sufficient for conventional scenarios; practical suggestions: use fmt.Scan for interactive simple input, use bufio.Scanner for line input or pipeline, use io.ReadAll for large block data, and always handle

SQLServer itself does not support serverless architecture, but the cloud platform provides a similar solution. 1. Azure's ServerlessSQL pool can directly query DataLake files and charge based on resource consumption; 2. AzureFunctions combined with CosmosDB or BlobStorage can realize lightweight SQL processing; 3. AWSathena supports standard SQL queries for S3 data, and charge based on scanned data; 4. GoogleBigQuery approaches the Serverless concept through FederatedQuery; 5. If you must use SQLServer function, you can choose AzureSQLDatabase's serverless service-free

It is recommended to use the in keyword to check whether a key exists in the dictionary, because it is concise, efficient and highly readable; 2. It is not recommended to use the get() method to determine whether the key exists, because it will be misjudged when the key exists but the value is None; 3. You can use the keys() method, but it is redundant, because in defaults to check the key; 4. When you need to get a value and the expected key usually exists, you can use try-except to catch the KeyError exception. The most recommended method is to use the in keyword, which is both safe and efficient, and is not affected by the value of None, which is suitable for most scenarios.

InstallJDK,setJAVA_HOME,installJavaExtensionPackinVSCode,createoropenaMaven/Gradleproject,ensureproperprojectstructure,andusebuilt-inrun/debugfeatures;1.InstallJDKandverifywithjava-versionandjavac-version,2.InstallMavenorGradleoptionally,3.SetJAVA_HO

UseconnectionpoolingwithHikariCPtoreusedatabaseconnectionsandreduceoverhead.2.UsePreparedStatementtopreventSQLinjectionandimprovequeryperformance.3.Fetchonlyrequireddatabyselectingspecificcolumnsandapplyingfiltersandpagination.4.Usebatchoperationstor

Mastering SpringCloud integration model is crucial to building modern distributed systems. 1. Service registration and discovery: Automatic service registration and discovery is realized through Eureka or SpringCloudKubernetes, and load balancing is carried out with Ribbon or LoadBalancer; 2. Configuration center: Use SpringCloudConfig to centrally manage multi-environment configurations, support dynamic loading and encryption processing; 3. API gateway: Use SpringCloudGateway to unify the entry, routing control and permission management, and support current limiting and logging; 4. Distributed link tracking: combine Sleuth and Zipkin to realize the full process of request visual pursuit.

MasterthePOMasadeclarativeblueprintdefiningprojectidentity,dependencies,andstructure.2.UseMaven’sbuilt-inlifecyclesandphaseslikecompile,test,andpackagetoensureconsistent,automatedbuilds.3.ManagedependencieseffectivelywithproperscopesanddependencyMana

Lazy loading only queries when accessing associations can easily lead to N 1 problems, which is suitable for scenarios where the associated data is not determined whether it is needed; 2. Emergency loading uses with() to load associated data in advance to avoid N 1 queries, which is suitable for batch processing scenarios; 3. Emergency loading should be used to optimize performance, and N 1 problems can be detected through tools such as LaravelDebugbar, and the $with attribute of the model is carefully used to avoid unnecessary performance overhead.
