How to convert []int8 to string

后端 未结 4 845
失恋的感觉
失恋的感觉 2020-12-11 05:04

What\'s the best way (fastest performance) to convert from []int8 to string?

For []byte we could do string(byteslice), but for

4条回答
  •  有刺的猬
    2020-12-11 06:02

    Not entirely sure it is the fastest, but I haven't found anything better. Change ba := []byte{} for ba := make([]byte,0, len(bs) so at the end you have:

    func B2S(bs []int8) string {
        ba := make([]byte,0, len(bs))
        for _, b := range bs {
            ba = append(ba, byte(b))
        }
        return string(ba)
    }
    

    This way the append function will never try to insert more data that it can fit in the slice's underlying array and you will avoid unnecessary copying to a bigger array.

提交回复
热议问题