Slice To Fixed Array Conversion
Convert a slice to a fixed-size array by value or to a shared array pointer, length-checking first so short frames never panic.
Code
package main
import "fmt"
// header 模拟协议帧的固定 4 字节头
type header [4]byte
func convertSliceToFixedArray(frame []byte) (header, error) {
if len(frame) < 4 {
return header{}, fmt.Errorf("frame too short: %d bytes", len(frame))
}
// Go 1.20 起切片可直接转为定长数组:按值复制,不共享底层数组
h := header(frame[:4])
return h, nil
}
func main() {
frame := []byte{0x1f, 0x8b, 0x08, 0x00, 0xde, 0xad}
h, err := convertSliceToFixedArray(frame)
if err != nil {
panic(err)
}
fmt.Printf("magic: %#x %x %x %x\n", h[0], h[1], h[2], h[3])
// 修改原切片不影响已转换出的数组:数据按值拷贝
frame[0] = 0xff
fmt.Printf("header unchanged: %#x\n", h[0])
// 转成数组指针则共享底层数组:改切片同步可见
ptr := (*[4]byte)(frame[:4])
frame[1] = 0xaa
fmt.Printf("via pointer reflects write: %x\n", ptr[1])
short := []byte{0x01, 0x02}
_, err = convertSliceToFixedArray(short)
fmt.Println("short frame:", err)
}How the snippet works
Slice To Fixed Array Conversion is built around the functions convertSliceToFixedArray and main.
Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.
Points of care
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Using it
Signature: func convertSliceToFixedArray(frame []byte) (header, error)
The run emits 4 labeled sections — magic:, header unchanged:, via pointer reflects write:, short frame: — one per step.
main sequences convertSliceToFixedArray; executing the file runs that flow once.
Key statements
return header{}, fmt.Errorf("frame too short: %d bytes", len(frame))
if err != nil {
panic(err)
}
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.
FAQ
- What happens when a call fails?
- By return value: each fallible call hands back an `error`, checked at 1 place here.
- What does Slice To Fixed Array Conversion print when run?
- No setup needed: run the file and look for labeled lines like `magic:`, `header unchanged:`, `via pointer reflects write:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.