string to bytes rust
To convert a string to bytes in Rust, you can use the as_bytes
method. Here's an example:
fn main() {
let my_string = String::from("Hello, world!");
let bytes = my_string.as_bytes();
for byte in bytes {
println!("{}", byte);
}
}
In this example, we create a String
called my_string
with the value "Hello, world!". We then call the as_bytes
method on my_string
to convert it into a byte slice. Finally, we iterate over the byte slice and print each byte.
The as_bytes
method returns a byte slice (&[u8]
) that represents the string's UTF-8 encoding. By iterating over the byte slice, you can access each individual byte of the string.
Keep in mind that the as_bytes
method only works with strings that are valid UTF-8. If your string contains non-UTF-8 characters, you may need to handle encoding conversions manually.
That's how you can convert a string to bytes in Rust.