Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go []byte to string conversion best practice

Online I have seen two methods converting a byte array to a string in Go.
Method 1:

func convert(myBytes byte[]) string {
   myString := string(myBytes[:])
   return myString
}

Method 2:

func convert(b []byte) string {
    return *((*string)(unsafe.Pointer(&b)))
}

What is the difference? Which one is faster? Which one should I use?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The first form copies the byte slice to a new array, and creates a string pointing to that. The second one creates a string pointing to the given byte slice.

The first one is safe, but has a copy operation. The second one is unsafe, and the program will break with hard to diagnose errors if you ever modify the contents of the given byte slice, because strings are supposed to be immutable. But it does not have a copy operation.

It is very unlikely that this is a bottleneck. Array copy is a fast operation. Use the first version.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading