Skip to content

Instantly share code, notes, and snippets.

@udhos
Created May 25, 2023 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save udhos/8499b3a4b7c0c06c0ad666f074bbb87a to your computer and use it in GitHub Desktop.
Save udhos/8499b3a4b7c0c06c0ad666f074bbb87a to your computer and use it in GitHub Desktop.
golang_string_to_bytes_and_back_again

bytes<->string without allocation. However, bytes can't be changed.

// StringToBytes converts string to byte slice without a memory allocation.
// The bytes must not be modified; doing so can cause
// the program to crash or behave unpredictably.
func StringToBytes(s string) []byte {
    return unsafe.Slice(unsafe.StringData(s), len(s))
}

// BytesToString converts byte slice to string without a memory allocation.
// The bytes passed must not be modified later;
// doing so can cause the program to crash or behave unpredictably.
func BytesToString(b []byte) string {
    return unsafe.String(&b[0], len(b))
}

golang/go#53003 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment