我想使用Decode
(https://golang.org/pkg/encoding/base64/#Encoding.Decode)来解码一段字节,并且想知道,给定这个方法签名,
func (enc *Encoding) Decode(dst, src []byte) (n int, err error)
如何选择dst
字节切片的大小,使其足够大以捕获输出。例如,此代码片段(改编自https://golang.org/pkg/encoding/base64/#Encoding.DecodeString)
package main
import (
"encoding/base64"
"fmt"
)
func main() {
str := "c29tZSBkYXRhIHdpdGggACBhbmQg77u/"
dst := make([]byte, 1024)
_, err := base64.StdEncoding.Decode(dst, []byte(str))
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("%s\n", dst)
}
印刷
some data with and
但是,如果我选择的尺寸dst太小(例如0),我会感到index out of range恐慌:
panic: runtime error: index out of range
goroutine 1 [running]:
encoding/base64.(*Encoding).decodeQuantum(0xc000084000, 0x1193018, 0x0, 0x0, 0xc000080f30, 0x20, 0x20, 0x4, 0x10, 0x10, ...)
/usr/local/Cellar/go@1.12/1.12.12/libexec/src/encoding/base64/base64.go:352 +0x567
encoding/base64.(*Encoding).Decode(0xc000084000, 0x1193018, 0x0, 0x0, 0xc000080f30, 0x20, 0x20, 0xc000080f38, 0x105779d, 0x10b16e0)
/usr/local/Cellar/go@1.12/1.12.12/libexec/src/encoding/base64/base64.go:500 +0x5aa
main.main()
/Users/kurt/Documents/Scratch/base64_decode.go:11 +0xb4
exit status 2
如何dst根据 的大小选择 的大小src以可靠地解码输入?
忽然笑
侃侃无极
相关分类