【问题标题】:Why does a byte that has been cast to a char not seem to have a proper type when pushing to a string?为什么在推送到字符串时,已转换为 char 的字节似乎没有正确的类型?
【发布时间】:2019-03-31 02:32:41
【问题描述】:

使用this 回答我正在尝试编写一个将 128 位整数转换为基数 62 数字的 Rust 函数。

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;
}

我使用as_bytes() 通过索引访问字母表中的字符并将字节转换回字符,打算将字符推送到String::push 的编码字符串。但是编译器对此抱怨,返回错误

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 `()`

我尝试使用to_owned() 为字符显式分配内存:

let character: char = (alphabet[(integer % base) as usize] as char).to_owned();
encoded = encoded.push( character );

但这返回了同样的错误。

为什么在推送到字符串时,已转换为 char 的字节似乎没有正确的类型?

【问题讨论】:

标签: string rust char


【解决方案1】:

这是因为 push 在 String 类型上不返回任何内容,而 ergo 返回 ()

将您的代码更改为:

// `->` 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
}

【讨论】:

    猜你喜欢
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多