Golang 展示BEGIN和END块
在这篇Go语言文章中,我们将写程序来展示BEGIN和END块,使用数字的求和、迭代和两个变量。
块用于将语句分组,块中描述的变量只能在该范围内使用,而不能在外部使用。它们还有助于代码的可读性。
步骤
- 步骤1 - 创建一个main包,在程序中声明fmt(格式化包)包,其中main生成可执行代码,而fmt帮助格式化输入和输出。
-
步骤2 - 创建一个main函数,在该函数中创建两个BEGIN和END块,用大括号括起来。
-
步骤3 - 在第一个块中,用两个名为a和b的变量接收两个数字,将这些数字相加并赋值给c。
-
步骤4 - 使用fmt包的Printf函数在控制台上打印出c。
-
步骤5 - 在第二个块中,接收一个人的姓名和年龄,并以与上一步类似的方式打印出来。
示例1
在这个示例中,我们将在main函数中创建两个BEGIN和END块。在第一个块中,我们将打印两个数字的和,在第二个块中,我们将打印一个人的姓名和年龄。
package main
import "fmt"
func main() {
{
a := 10
b := 20
c := a + b
fmt.Printf("The sum of %d and %d is %d\n", a, b, c)
}
{
name := "Ronit"
age := 34
fmt.Printf("%s is %d years old\n", name, age)
}
}
输出
The sum of 10 and 20 is 30
Ronit is 34 years old
示例2
在这个示例中,我们将创建两个开始和结束块,并使用匿名函数来执行开始和结束块。在第一个块中执行一些语句,而在第二个块中使用迭代打印数字。
package main
import "fmt"
func main() {
func() {
defer fmt.Println("This statement is executed last in the program")
fmt.Println("This statement is executed first in the program")
}()
func() {
for i := 1; i<= 6; i++ {
defer fmt.Printf("%d ", i)
}
}()
}
输出
This statement is executed first in the program
This statement is executed last in the program
6 5 4 3 2 1
示例3
在这个示例中,我们将编写一个Go语言程序,使用两个变量a和b来演示BEGIN和END块。
package main
import "fmt"
func main() {
{
a := 20
fmt.Println("Value of x inside begin block:", a)
}
{
b := "Hello, alexa!"
fmt.Println("Value of y inside begin block:", b)
}
}
输出
Value of x inside begin block: 20
Value of y inside begin block: Hello, alexa!
结论
我们执行了演示开始和结束块的程序。在第一个示例中,我们创建了两个块,并使用fmt包打印输出,而在第二个示例中,我们在打印块的输出时使用了defer关键字,在第三个示例中,我们使用了两个变量来执行该程序。