duanou1904 2015-09-25 15:11
浏览 74

如何在Go中不使用for循环的情况下初始化数组?

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
}
  • 写回答

2条回答 默认 最新

  • duanfeigui6655 2015-09-25 15:18
    关注

    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?

    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名