Will
[]T
Slices are converted to
[]byte
Convert other types of arrays to arrays in C-like languages char
:
interface{}) (data []byte) { sv := reflect.ValueOf(slice) if sv.Kind() != reflect.Slice { panic(fmt.Sprintf("ByteSlice called with non-slice value of type %T", slice)) } h := (*reflect.SliceHeader)((unsafe.Pointer(&data))) h.Cap = sv.Cap() * int(sv.Type().Elem().Size()) h.Len = sv.Len() * int(sv.Type().Elem().Size()) h.Data = sv.Pointer() return}
Based on this function, we can easily invoke []byte
the function of the type parameter:
func SaveImageData(name string, data []color.RGBA) error { return ioutil.WriteFile(name, ByteSlice(data), 0666)}
Precautions
The conversion operation has a certain risk, the user needs to ensure their own security. These are mainly related to the following types:
- When a struct contains pointers, the conversion can cause garbage collection problems.
- If it is a
[]byte
turn []T
may cause the start address to be misaligned (it is []byte
possible to slice from an odd position).
- The conversion operation may depend on the current system, and there are differences between different types of processors.
The benefits of this conversion operation are performance and similar void*
generics, which are cgo
ideal for use with interfaces.
http://my.oschina.net/chai2010/blog/266864
Conversion between different types of slices in the go language