
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Golang Program to Demonstrate Argument Passing to Block
In this article, we are going to learn how to demonstrate the argument to block using the user-defined function, iterations, and square of numbers . A block is created using curly braces with a definite begin and end braces. The different operations are performed inside the braces.
Algorithm
Step 1 ? Import the required packages in the program
Step 2 ? Create a main function and in there create a slice
Step 3 ? Use a function to pass the argument and print the values with the help of iteration
Step 4 ? Print statement is executed Println function from fmt package
Example 1
In this example, we will write a Golang program to demonstrate the argument passing to block using an anonymous function in which the slice values will be passed as arguments and those values will be printed on the console
package main import "fmt" func main() { values := []int{10, 20, 30, 40, 50} for _, value := range values { func(n int) { fmt.Println("Value:", n) } (value) } }
Output
Value: 10 Value: 20 Value: 30 Value: 40 Value: 50
Example 2
In this illustration, we will write a Golang program to demonstrate the argument passing to block using iteration, here a slice of strings will be created in the block which will be iterated and printed on the console.
package main import "fmt" func main() { name_values := []string{"Varun", "Rajat", "Pulkit", "Kajal"} for _, name := range name_values { printName(name) } } func printName(name string) { fmt.Println("Name:", name) }
Output
Name: Varun Name: Rajat Name: Pulkit Name: Kajal
Example 3
In this example, we will write a Golang program to demonstrate the argument passing to block using square of numbers.
package main import "fmt" func main() { demo_block := func(val int) { fmt.Printf("The square of %d is %d\n", val, val*val) } demo_block(6) demo_block(8) }
Output
The square of 6 is 36 The square of 8 is 64
Conclusion
We compiled and executed the program of demonstrating the argument passing to block using three examples. In the first example, we used an anonymous function to pass the argument, in the second example we created a function which is called every time loop runs and in the third example, we squared the values taken in the argument to depict the use of block.