Home > Backend Development > Golang > How to Convert a Fixed-Size Byte Array to a String in Go?

How to Convert a Fixed-Size Byte Array to a String in Go?

Linda Hamilton
Release: 2024-12-14 08:10:20
Original
956 people have browsed it

How to Convert a Fixed-Size Byte Array to a String in Go?

Converting [Size]byte to String in Go

When working with byte arrays in Go, it may be necessary to convert them to strings for further processing. Let's consider an example where you encounter an error while attempting to convert a sized byte array obtained from md5.Sum() to a string:

data := []byte("testing")
var pass string
var b [16]byte
b = md5.Sum(data)
pass = string(b)
Copy after login

This code will result in the following error:

cannot convert b (type [16]byte) to type string
Copy after login

The error occurs because the byte array b is fixed in size (16 bytes), while Go requires strings to be of variable length. To resolve this issue, you can refer to b as a slice instead of a fixed-size array:

pass = string(b[:])
Copy after login

By using slice syntax, you create a new string containing the bytes from b without specifying a fixed length. The result is a string that represents the bytes effectively. This approach allows you to convert any sized byte array to a string in Go.

The above is the detailed content of How to Convert a Fixed-Size Byte Array to a String in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template