如何在Go中不使用for循环来初始化数组? [英] How do I initialize an array without using a for loop in Go?

查看:137
本文介绍了如何在Go中不使用for循环来初始化数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组 A 的布尔值,用整数索引 0 n ,全部初始设置为 true



我目前的实现是:

  for i:= 0;我< N; i ++ {
A [i] = true
}


解决方案

对循环使用是最简单的解决方案。创建一个数组或切片将始终返回一个归零值。在 bool 的情况下,所有值都是 false (类型为code> bool的零值)。



请注意,使用复合文字,您可以创建并初始化切片或数组,但不会更短:

  b1:= [] bool {true,true,true} 
b2:= [3] bool {true,true,true}

如果你不想为循环使用,你可以通过引入一个常量来缩短它值 true

  const T = true 
b3 := [] bool {T,T,T}

如果 n 是很大的,对于是最简单的解决方案。



或者你可以切换逻辑你的应用程序,并使用数组或切片将切片中的否定值存储起来,这样,all-false零值将是一个很好的初始值值。我的意思是,如果您的切片要存储如果文件存在,您可以更改逻辑,以便切片存储文件是否缺失

 呈现:= [] bool {true,true,true,true,true,true} 

//相当于:
$ b missings:= make([] bool,6)//所有false
// missing = false表示不丢失,表示存在)

另外请注意,使用特定值填充数组或切片称为memset操作。 Go没有内建函数,但为了一个有效的解决方案,请参阅以下问题:

是否有类似的memset?


I have an array A of boolean values, indexed by integers 0 to n, all initially set to true.

My current implementation is :

for i := 0; i < n; i++ {
    A[i] = true
}

解决方案

Using a for loop is the simplest solution. Creating an array or slice will always return you a zeroed value. Which in case of bool means all values will be false (the zero value of type bool).

Note that using a Composite literal you can create and initialize a slice or array, but that won't be any shorter:

b1 := []bool{true, true, true}
b2 := [3]bool{true, true, true}

If you don't want to use a for loop, you can make it a little shorter by introducing a constant for the value true:

const T = true
b3 := []bool{T, T, T}

If n is big, for is the simplest solution.

Or you could switch the logic of your application, and use the array or slice to store the negated values in the slice, and that way the "all-false" zero value would be a good initial value. What I mean is that if your slice is to store if files are present, you could change the logic so the slice stores whether files are missing:

presents := []bool{true, true, true, true, true, true}

// Is equivalent to:

missings := make([]bool, 6) // All false
// missing=false means not missing, means present)

Also note that filling an array or slice with a specific value is known as a "memset" operation. Go does not have a builtin function for that, but for an efficient solution see this question:

Is there analog of memset in go?

这篇关于如何在Go中不使用for循环来初始化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆