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 51寻迹小车定点寻迹
  • ¥15 爬虫爬取网站的一些信息
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件