How to convert &str to &[u8] in Rust?
Hello everyone! I just started learning Rust and encountered a problem that seems simple, but I can't find the right solution. I need to pass a string to a function that expects a byte slice `&[u8]`. For example, I'm writing a simple program for working with files: I want to write a string to a file using `write`, but it takes `&[u8]`, while I have `&str`.
Here's my code:
```rust
use std::fs::File;
use std::io::Write;
fn main() {
let s = "Привет, мир!";
let mut file = File::create("test.txt").unwrap();
file.write(s).unwrap(); // Error: expected &[u8], found &str
}
```
I get a compilation error: `expected &[u8], found &str`. I understand that strings in Rust are UTF-8, and bytes are just a sequence of bytes. But how do I get a byte slice from a string? I've tr
No answers yet.
Log in to leave an answer
Blogs