How to convert []int8 to string

后端 未结 4 948
失恋的感觉
失恋的感觉 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 05:49

    What is sure from "Convert between slices of different types" is that you have to build the right slice from your original int8[].

    I ended up using rune (int32 alias) (playground), assuming that the uint8 were all simple ascii character. That is obviously an over-simplification and icza's answer has more on that.
    Plus the SliceScan() method ended up returning uint8[] anyway.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        s := []int8{'a', 'b', 'c'}
        b := make([]rune, len(s))
        for i, v := range s {
            b[i] = rune(v)
        }
        fmt.Println(string(b))
    }
    

    But I didn't benchmark it against using a []byte.

提交回复
热议问题