Go語言檢查切片是否為空


本文將透過多種示例來檢查切片是否為空。切片就像陣列一樣,是一系列元素的序列。陣列是固定長度的元素序列,而切片是動態陣列,這意味著它的值不是固定的,可以更改。切片比陣列更高效、更快,並且它們是按引用傳遞而不是按值傳遞。讓我們透過示例學習如何執行它。

語法

func append(slice, element_1, element_2…, element_N) []T

append 函式用於向陣列切片新增值。它接受多個引數。第一個引數是要向其中新增值的陣列,後跟要新增的值。然後,該函式返回包含所有值的最終陣列切片。

演算法

  • 步驟 1 − 建立一個 package main 並宣告程式中的 fmt(格式包),其中 main 生成可執行程式碼,fmt 幫助格式化輸入和輸出。

  • 步驟 2 − 建立一個 main 函式,並在該函式中初始化一個切片並使用 append 函式填充值。

  • 步驟 3 − 使用 Go 語言中的 print 語句在控制檯上列印切片。

  • 步驟 4 − 檢查一個條件:如果切片的長度等於 0,則在控制檯上列印切片為空,否則列印切片不為空。

  • 步驟 5 − 使用 fmt.Println() 函式執行 print 語句,其中 ln 表示換行。

使用 Len 方法

在這個例子中,我們將看到如何使用 len 方法來查詢切片是否為空。len 方法用於計算切片的長度。讓我們藉助演算法和程式碼來理解這個例子。

示例

package main
import "fmt"

//create a function main
func main() {

	var slice []int  // initialize slice

	slice = append(slice, 1) //fill the slice using append function
	slice = append(slice, 2)
	slice = append(slice, 3)
	slice = append(slice, 4)

	fmt.Println("The slice created by user is:", slice)

	if len(slice) == 0 {
		fmt.Println("Slice is empty")  
	} else {
		fmt.Println("Slice is not empty") 
	}

}

輸出

The slice created by user is: [1 2 3 4]
Slice is not empty

使用 Nil 值

在這個例子中,我們將透過將切片與 nil 值進行比較來檢視切片是否為空。我們將比較建立的切片與 nil 值。讓我們藉助演算法和程式碼來理解這個例子。

示例

package main
import "fmt"
func main() {

	var slice []int //initialize a slice
	slice = append(slice, 1)  //fill the slice using append method
	slice = append(slice, 2)
	slice = append(slice, 3)
	slice = append(slice, 4)

	fmt.Println("The slice created by user is:", slice) 

	if slice == nil {
		fmt.Println("Slice is empty") 
	} else {
		fmt.Println("Slice is not empty") 
	}
}

輸出

The slice created by user is: [1 2 3 4]
Slice is not empty

使用切片的索引

在這個例子中,我們將透過將索引值與零進行比較來檢視切片是否為空。我們將比較建立的切片的索引與零值。讓我們藉助演算法和程式碼來理解這個例子。

示例

package main
import "fmt"
func main() {

	var slice []int //create slice
	slice = append(slice, 1) //fill elements using append method
	slice = append(slice, 2)
	slice = append(slice, 3)
	slice = append(slice, 4)

	fmt.Println("The slice created by user is:", slice)
	if slice[0] == 0 {
		fmt.Println("Slice is empty")
	}else {
		fmt.Println("Slice is not empty") 
	}
}

輸出

The slice created by user is: [1 2 3 4]
Slice is not empty

結論

在上面的程式中,我們使用了三個例子來檢查切片是否為空。在第一個例子中,我們使用了 len 方法來檢查切片是否為空。在第二個例子中,我們使用了 nil 來比較切片,在第三個例子中,我們使用了索引。

更新於: 2023年1月23日

5K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告