0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
jla
  • 4,191
  • 3
  • 27
  • 44
  • 2
    https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=03dec7e73c7568268666abae21c30d63, did you read the book ? – Stargateur Mar 31 '19 at 03:24

1 Answers1

1

This is because push on String type returns nothing and ergo returns a ()

Change your code to:

// `->` specifies return type
fn encode_as_chars( mut integer: u128 ) -> String {
    let alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".as_bytes();
    let base: u128 = 62;
    let mut encoded: String = "".to_string(); // you need to initialize every variable in Rust

    while integer != 0 {
        encoded.push( alphabet[(integer % base) as usize] as char );
        integer /= base;
    }

    encoded // return encoded
}
sn99
  • 843
  • 8
  • 24