Go(Golang)中Bool的切片或阵列

1,734 阅读2分钟

概述

在Golang中也可以创建一个bool数据类型的片断或数组。事实上,在Go中可以创建任何数据类型的片断或数组。本教程包含了在Golang中创建bool数据类型的分片或数组的简单例子。

这里要补充的是,在Golang中,数组是固定大小的,而片断可以有可变大小。更多的细节在这里

数组- https://golangbyexample.com/understanding-array-golang-complete-guide/

片 - https://golangbyexample.com/slice-in-golang/

Bool的片断

package main

import "fmt"

func main() {

	//First Way
	var booleans_first []bool
	booleans_first = append(booleans_first, true)
	booleans_first = append(booleans_first, false)
	booleans_first = append(booleans_first, true)

	fmt.Println("Output for First slice of booleans")
	for _, c := range booleans_first {
		fmt.Println(c)
	}

	//Second Way
	booleans_second := make([]bool, 3)
	booleans_second[0] = false
	booleans_second[1] = true
	booleans_second[2] = false

	fmt.Println("\nOutput for Second slice of booleans")
	for _, c := range booleans_second {
		fmt.Println(c)
	}
}

输出

Output for First slice of booleans
true
false
true

Output for Second slice of booleans
false
true
false

我们有两种方法来创建一个bool的切片。第一种方法是

var booleans_first []bool
booleans_first = append(booleans_first, true)
booleans_first = append(booleans_first, false)
booleans_first = append(booleans_first, true)

第二种方式是,我们使用make命令来创建一个bool的切片

booleans_second := make([]bool, 3)
booleans_second[0] = false
booleans_second[1] = true
booleans_second[2] = false

无论哪种方式都可以。这就是我们如何创建bool的片断的方法

布尔的数组

package main

import "fmt"

func main() {

	var booleans_first [3]bool

	booleans_first[0] = true
	booleans_first[1] = false
	booleans_first[2] = true

	fmt.Println("Output for First Array of booleans")
	for _, c := range booleans_first {
		fmt.Println(c)
	}

	booleans_second := [3]bool{
		false,
		true,
		false,
	}

	fmt.Println("\nOutput for Second Array of booleans")
	for _, c := range booleans_second {
		fmt.Println(c)
	}
}

输出

Output for First Array of booleans
true
false
true

Output for Second Array of booleans
false
true
false

我们有两种创建数组的方法。第一种方法是

var booleans_first [3]bool
booleans_first[0] = true
booleans_first[1] = false
booleans_first[2] = true

第二种方式,我们直接用创建的布尔值初始化数组

booleans_second := [3]bool{
	false,
	true,
	false,
}

请看我们的 Golang 高级教程。这个系列的教程是精心设计的,我们试图用例子来涵盖所有的概念。本教程是为那些希望获得专业知识和扎实了解Golang的人准备的 - Golang高级教程

如果你有兴趣了解如何在Golang中实现所有设计模式。如果是的话,那么这篇文章就是为你准备的--所有设计模式 Golang

The postSlice or Array of Bool in Go (Golang)appeared first onWelcome To Golang By Example.