douhoushou8385 2019-04-19 17:32
浏览 56
已采纳

添加[]字节附加切片[]字节

I began to learn the language of GO and I do not quite understand something, maybe I'm just confused and tired. Here is my code, there is an array of result (from encoded strings, size 2139614 elements). I need to decode them and use them further. But when I run an iteration, the resultrips is twice as large and the first half is completely empty. Therefore, I make a slice and add to it the desired range.

Why it happens?

It might be easier to decode the result immediately and re-record it, but I don’t know how to do it, well)))

maybe there is a completely different way and as a beginner I don’t know it yet

        result := []string{}

    for i, _ := range input {
        result = append(result, i)
    }
    sort.Strings(result)

    rips := make([][]byte, 2139614)

    for _, i := range result {
        c := Decode(i)
        c = c[1:37]
        rips = append(rips, c)
    }
        //len(result) == 2139614

    for i := 2139610; i < 2139700; i++ {
        fmt.Println(i, rips[i])
    }

    resultrips := rips[2139614:]
    for _,i := range resultrips {
        fmt.Println(i)
    }

    fmt.Println("All write: ", len(resultrips))

and this question: I do it right if I need an array of byte arrays (I do it so as not to do too much work and will check the values in bytes, because there is no any coding) ???

rips := make([][]byte, 2139614) //array []byte

in the end, I need an array of the type of the set in C ++ to check if there is an element in my set in C ++ it was code: if (resultrips.count > 0) { ... }

  • 写回答

1条回答 默认 最新

  • doubingling4706 2019-04-19 17:36
    关注

    When you write:

    make([][]byte, 2139614)
    

    This creates a slice with length and capacity equal to 2139614. When you append to a slice, it always appends after the last element, thereby increasing the length. If you want to pre-allocate a large slice so that you can append into it, you want to specify a length of 0:

    make([][]byte, 0, 2139614)
    

    This pre-allocates 2139614 elements, but with a length of 0, subsequent append calls will start at the beginning of the slice; after the first append it will have a length of 1, and it will not need to have increased its capacity.

    Length vs capacity is covered in the Tour of Go: https://tour.golang.org/moretypes/13

    A quick note based on the text of your question - remember that slices and arrays are not the same thing. Arrays have a compile-time fixed length and their capacity is synonymous with their length. Slices are backed by arrays but have runtime dynamic independent length and capacity.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试