Go語言程式演示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

在這個例子中,我們將建立兩個BEGIN和END塊,並將使用匿名函式來執行BEGIN和END塊。在第一個塊中將執行一些語句,而在第二個塊中將使用迭代列印數字。

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!

結論

我們執行了演示BEGIN和END塊的程式。在第一個示例中,我們建立了兩個塊並使用fmt包列印輸出;在第二個示例中,我們在列印塊的輸出時使用了defer關鍵字;在第三個示例中,我們使用了兩個變數來執行程式。

更新於:2023年5月3日

瀏覽量:138

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告