njhkugk6i76g6gi6gi7g6
njhkugk6i76g6gi6gi7g6

Reputation: 61

How to index an &str and push the chosen element to String?

To complete a task on codewars, i have to be able to push one element of str to String. I have tried this:

str_to.push_str(from_utf8(&s.as_bytes([count_alpha_all..count_alpha_all)))

(countalpha is an integer)

But there is an error:

str_to.push_str(from_utf8(&s.as_bytes([count_alpha_all..count_alpha_all]));
   |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&str`, found enum `Result`
   |
   = note: expected reference `&str`
                   found enum `Result<&str, Utf8Error>`

How to fix that?

Upvotes: 1

Views: 778

Answers (2)

Netwave
Netwave

Reputation: 42678

You can use String::push_str over a slice of the str:

let s = "Foo Bar";
let mut res = String::new();
res.push_str(&s[4..]);

Prints out: Bar

Playground

Upvotes: 2

foragerDev
foragerDev

Reputation: 1409

There error is straight forward from_utf8 returns Result<String, FromUtf8Error>. So you simply have to do this.

str_to.push_str(from_utf8(&s.as_bytes([count_alpha_all..count_alpha_all)).unwrap());

If from_utf8 will fail program will panic.

Upvotes: 0

Related Questions