How to get a character of a string by index in Rust? String indexing
Hello everyone! I just started learning Rust and encountered a problem that confuses me a lot. I'm used to other programming languages, like Python or C++, where you can simply write `my_string[0]` and get the first character. In Rust, I tried to do the same thing, and the compiler gave me an error.
Here's my code:
```rust
fn main() {
let hello = String::from("Привет");
let first_char = hello[0]; // Error!
println!("First character: {}", first_char);
}
```
The compiler says something about `the trait bound 'String: Index<{integer}>' is not satisfied`. Honestly, I don't understand why strings can't be indexed like regular arrays. After all, a string is a sequence of characters, right? I tried googling, but the answers on English Stack Overflow are too complicated for a beginner.
No answers yet.
Log in to leave an answer