Reputation: 61
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
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
Upvotes: 2
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