我一直在做 Code of Code 來學習 Rust,在第 3 天我最終寫了這個:
fn ones_per_bit(lines:&Vec<String>, bitcount:usize) -> Vec<u32> {
let mut out: Vec<u32> = Vec::new();
out.resize(bitcount, 0);
for line in lines {
for (i, c) in line.chars().enumerate() {
if c == '1' { out[i] = 1; }
}
}
return out;
}
然后復制/粘貼它,以便我可以用 a&Vec<&String>而不是&Vec<String>. 這有效,但為了避免重復函式體,我希望使用泛型,但我的幼稚實作如下所示:
fn ones_per_bit<T>(lines:&Vec<T>, bitcount:usize) -> Vec<u32> {
let mut out: Vec<u32> = Vec::new();
out.resize(bitcount, 0);
for line in lines {
for (i, c) in line.chars().enumerate() {
if c == '1' { out[i] = 1; }
}
}
return out;
}
這導致:
error[E0599]: no method named `chars` found for reference `&T` in the current scope
--> main.rs:44:24
|
44 | for (i, c) in line.chars().enumerate() {
| ^^^^^ method not found in `&T`
所以我在這里缺少一個概念。我似乎需要告訴 rust 在泛型型別上期望什么型別的方法,但我不確定最好的方法(或者我應該在這里使用更好的語言功能)。
uj5u.com熱心網友回復:
您在這里想要的是一種可以取消參考的型別&str。
這通常通過<T: AsRef<str>>通用約束來完成:
fn ones_per_bit<T: AsRef<str>>(lines: &[T], bitcount:usize) -> Vec<u32> {
let mut out: Vec<u32> = Vec::new();
out.resize(bitcount, 0);
for line in lines {
for (i, c) in line.as_ref().chars().enumerate() {
if c == '1' { out[i] = 1; }
}
}
return out;
}
旁注:由于deref coercion,將引數宣告為&[T]而不是&Vec[T]使其適用于 bot vec 參考和切片。請參閱為什么不鼓勵接受對 String (&String)、Vec (&Vec) 或 Box (&Box) 的參考作為函式引數?
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/394605.html
上一篇:打字稿:通用未推斷
