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 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误