使用this回答我正在尝试编写一个Rust函数,它将128位整数转换为基数为62的数字。
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()
通过索引访问字母表中的字符并将字节强制转换为char,打算使用String::push
将char推送到编码的字符串。但是编译器抱怨这个,返回错误
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()
显式地为char分配内存:
let character: char = (alphabet[(integer % base) as usize] as char).to_owned();
encoded = encoded.push( character );
但是这返回了同样的错误。
为什么在推送到字符串时,已转换为char的字节似乎没有正确的类型?
这是因为字符串类型的push
不返回任何内容而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
}