Using this answer I'm attempting to write a Rust function that converts a 128 bit integer into a base 62 number.
fn encode_as_chars(mut integer: u128) {
let alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".as_bytes();
let base: u128 = 62;
let mut encoded: String;
while integer != 0 {
encoded = encoded.push(alphabet[(integer % base) as usize] as char);
integer /= base;
}
encoded;
}
I access a character in the alphabet by index using as_bytes()
and cast the byte back to a char, intending to push the char to the encoded string with String::push
. However the compiler complains about this, returning the error
error[E0308]: mismatched types
--> src/lib.rs:7:19
|
7 | encoded = encoded.push(alphabet[(integer % base) as usize] as char);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found ()
|
= note: expected type `std::string::String`
found type `()`
I tried to explicitly allocate memory to the char by using to_owned()
:
let character: char = (alphabet[(integer % base) as usize] as char).to_owned();
encoded = encoded.push( character );
but this returned the same error.
Why does a byte that has been cast to a char not seem to have a proper type when pushing to a string?