Rust Lang

Converting String to Bytes and Bytes to String in Rust

Strings are some of the most common data types in any programming language. Consequently, it is a common task to manipulate the string values including trimming, searching, pattern matching, and more.

One typical string operation is converting a string to bytes and vice versa. This post explores how to convert a Rust string to bytes and a set of bytes to a string.

Rust Strings

In Rust, a string refers to a dynamically sized, UTF-8 encoded heap-allocated string. It is represented as a string data type which is implemented in the Rust standard library which allows you to quickly use and format the string data in your programs.

We can define a string as follows:

let my_string = String::from("Hello, world!");

 

Rust Bytes

In Rust, a byte refers to an 8-bit unsigned integer that represents a single data byte. In Rust, it is denoted by the u8 data type which is defined in Rust’s standard library which allows you to work with the byte data.

We can define a byte value as follows:

let my_byte: u8 = 97;

 

Convert the Strings to Bytes

We can use the as_bytes method that is provided by the string type to convert a Rust string to bytes. This method returns a &[u8] slice, a reference to an array of bytes.

Example:

fn main() {
    let my_string = String::from("Hello, world!");
    let my_bytes = my_string.as_bytes();

    println!("{:?}", my_bytes);
}

 

This should return a byte slice as shown in the following:

[72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]

 

Convert the Bytes to String

To convert the Rust bytes to a string, we can use the from_utf8 method which is provided by the string type. The method takes a &[u8] slice as an argument and returns a Result<String, FromUtf8Error>.

The method returns a result. In addition, it returns the converted string if the conversion is successful. It returns an error if the bytes cannot be converted to a valid UTF-8 string.

Example:

fn main() {
    let my_bytes = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33];
    let my_string = String::from_utf8(my_bytes.to_vec()).unwrap();

    println!("{}", my_string);
}

 

In the previous example, we convert the array to a Vec<u8> using the to_vec method.

Next, we convert the resulting vector to a string using the from_utf8 method. Finally, we use the unwrap method to extract the string from the result.

Running the code above:
   Compiling read_file_line v0.1.0 (convert)
    Finished dev [unoptimized + debuginfo] target(s) in 0.41s
     Running `target\debug\convert.exe
Hello, world!

 

As you can see, the code returns the UTF-8 string equivalent.

Conclusion

We covered the fundamentals of working with strings and byte data types in the Rust programming language. We also learned how we can convert a string to a byte slice and vice versa.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list