Conversion between different types of slices in the go language

Source: Internet
Author: User

Will []TSlices 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.