How to get a character from a string by index in Rust?
I just started learning Rust and encountered a problem that seems very strange to me. In other languages, like Python or JavaScript, I can easily get a character from a string by index: `"hello"[0]` gives me `'h'`. But when I tried to do the same in Rust, the compiler gave an error.
Here's my code:
```rust
fn main() {
let s = String::from("Привет, мир!");
let first = s[0]; // Error!
println!("First character: {}", first);
}
```
The compiler says something like: "the type `String` cannot be indexed by `{integer}`". I understand that Rust is a safe language, but why can't I just get a character by index? In other languages it works! How do I correctly get a character from a string? What am I doing wrong?
I need to process each character of the string individually.
No answers yet.
Log in to leave an answer
Blogs
Microservices in TypeScript: Architecture and Practice