How to store values in struct using for loop in GO

In this article, we shall be discussing how to store values into structs fields using for loop in Golang with practical examples.

 

Overview

In a nutshell, a for loop is one of the code structures that is executed repetitively on a piece of code, until certain conditions are met. In programming, several activities are automated given an array of objects or any data structures.

Advertisement

In Golang, We only use for loop statement to execute a given task array/object, file, etc. based on the length of the slice, array, or the counter variables.

The following are the most used for loop cases in Golang

 

How to declare for-clause and conditional loop

In Go, we can declare use for loop in following ways :-

 

RangeClause

We use the range clause to handle channel data, slice, array, etc data types since it's neat and easy to read.

Its syntax is :=

for key,value := range dataStructure{}

The key is the index value being accessed in every loop, value represents the actual values on each iteration and dataStructure its the datastructure whose values being accessed, i can be of type slice, string, map or channel. We can append the values from dataStructure into a struct or handle it in the required manner.

Advertisement

For example:

for key,value := range slice/array/map.. {[results actioned]}

Implementation:=

package main

import "fmt"

var results = []string{"Javascript", "Go", "Java", "Kotlin"}

func main() {
	fmt.Printf("Key : value \n")

	for key, value := range results {
		fmt.Printf("%v : %v \n", key, value)
	}

}

Results:=

$ go run main.go
Key : value 
0 : Javascript 
1 : Go 
2 : Java 
3 : Kotlin 

 

ForClause

It contains initial statement, condition and then increment or decrement statement. Its implemented as follows

for [initial value];[check conditions];[increment/decrement statement]{[results]}

Example

package main

import "fmt"

func main() {

	for i := 0; i < 10; i++ {
		fmt.Println(i)
	}
}

 

ConditionalClause

Its a a condition embeded inside the for loop statement using If ..else conditions. Its implemented as follows :=

for {
   if [value] { [actions]}
      // more actions
}

Example:

package main

import (
"fmt"
 "os")

file := "file.txt"
func main() {
	for {
	data, err := os.ReadFile(file}
	if err != nil {
	fmt.Println(err)
	}
	fmt.Println(string(data))
	}
}

 

Storing slice data into struct using for range loop

Slice in Golang is an array that stores variables of the same types . Its size is not fixed and can't store elements of different types. It has index, length, and capacity properties. Below is how we can use for range loop to store slice variables into a struct in Golang.

package main

import (
	"fmt"
)

type DataStr struct {
	Key   int
	Value string
}

func main() {
	data := []string{"AWS", "GoLinux", "Google", "Linux", "Chrome"}

	var res []DataStr
	for key, value := range data {
		res = append(res, DataStr{
			key, value,
		})
	}
	fmt.Println("Array of strings stored into structs", res)
}

Output:

$ go run main.go
Array of strings stored into structs [{0 AWS} {1 GoLinux} {2 Google} {3 Linux} {4 Chrome}]

Explanation:- In the above code, we are using for range loop to iterate through a slice of string values and appending its values to a struct as key and value of integer and string type respectively. The append enables us to store values into a struct.

 

Summary

In this article, we have discussed various ways of creating a for-loop statement in Golang. Each case is used in different scenarios. Mostly for key,val:= range{} is mostly preferred in most situations for its ease of usability throughout the code.

 

Reference

for_loop in struct and maps

Advertisement

 

Categories GO

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X