Home > Backend Development > Golang > How Can I Efficiently Convert a String to a Byte Array in Go?

How Can I Efficiently Convert a String to a Byte Array in Go?

Mary-Kate Olsen
Release: 2024-12-21 11:36:14
Original
606 people have browsed it

How Can I Efficiently Convert a String to a Byte Array in Go?

Assigning String to Byte Array

In your code, you've successfully assigned the string "abc" to a byte array using a range loop. However, there is a simpler and equally secure method to achieve the same result.

Using []byte() Function

Instead of manually converting each character to a byte and assigning it to the array, you can use the []byte() function to perform the conversion. This function returns a slice of bytes representing the contents of the string.

[]byte("Here is a string....")
Copy after login

This code will create a byte array with the following values:

[72 101 114 101 32 105 115 32 97 32 115 116 114 105 110 103 46 46 46]
Copy after login

Using this method is concise and ensures the correct conversion of characters to bytes. It is important to note that the []byte() function returns a slice of bytes, which is not the same as an array. If you require an array, you can use the copy() function to copy the slice into an array.

var arr [20]byte
copy([]byte("Hello, world!"), arr[:])
Copy after login

This code will copy the bytes from the slice into the first 20 elements of the array arr.

The above is the detailed content of How Can I Efficiently Convert a String to a Byte Array 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