'Generic string or byte slice read in one allocation
Is it possible for a generic Go function to read data as either a string or a byte slice, and have only one memory allocation either way?
The following function does 1 allocation for byte slices and 2 allocations for strings.
func ReadN[S string | []byte](r io.Reader, n int) (S, error) {
buf := make([]byte, n)
n, err := io.ReadFull(r, buf)
return S(buf)[:n], err
}
No unsafe permitted in this case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
