dongshou6041 2018-11-18 03:10
浏览 23
已采纳

切片vs数组用于已知长度的数据

When dealing with something like a sha256 hash which has a known length of 32 bytes– is it more idiomatic to work with []byte slices or [32]byte arrays?

I'm a bit new to go– but intuitively it feels like while working with a [32]byte array to store a hash is nice and explicit, it's actually quite cumbersome to manipulate and requires all sorts of strange things like copying the array into a new buffer slice to manipulate as []byte.

  • 写回答

2条回答 默认 最新

  • douchuituo3032 2018-11-19 21:53
    关注

    Looking at the Go standard library, it looks like arrays are often used for something like a hash of known length. e.g sha256.Sum256 returns a [sha256.Size]byte where sha256.Size is 32. Or looking at the digest struct that implements the hash.Hash interface in sha256 it contains [chunk]byte where chunk is 64, the sha256 blocksize.

    I think it is typical to use arrays to avoid unnecessary memory allocation. To take advantage of algorithms that operate on slices of a variable length you can convert the array to a slice without copying with x[:].

    package main
    
    import (
        "crypto/sha256"
        "fmt"
    )
    
    type myHash struct {
        x [32]byte
    }
    
    func print(b []byte) {
        fmt.Print(b)
    }
    
    func main() {
        b := []byte("Hello world!")
        h := myHash{x: sha256.Sum256(b)}
        print(h.x[:])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥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#的问题:自动化测试