-1
我是Rust的新手。以下是查找這兩個數字的索引的代碼,以便它們合計到一個特定的目標。錯誤:並非所有的控制路徑都返回一個值[E0269]
use std::collections::HashMap;
fn two_sum(nums: &[i32], target: i32) -> [usize;2] {
let mut map: HashMap<i32, usize> = HashMap::new();
for i in 0..nums.len() {
let want = target - nums[i];
match map.get(&nums[i]) {
Some(&seen) => return [seen, i],
_ => map.insert(want, i),
};
}
[0usize, 0usize];
}
fn main() {
let nums = [1,3,7,4];
let res = two_sum(&nums, 10);
println! ("{},{}", res[0], res[1]);
}
我喜歡下面
src/bin/2sum.rs:3:1: 15:2 error: not all control paths return a value [E0269]
src/bin/2sum.rs:3 fn two_sum(nums: &[i32], target: i32) -> [usize;2] {
src/bin/2sum.rs:4 let mut map: HashMap<i32, usize> = HashMap::new();
src/bin/2sum.rs:5
src/bin/2sum.rs:6 for i in 0..nums.len() {
src/bin/2sum.rs:7 let want = target - nums[i];
src/bin/2sum.rs:8 match map.get(&nums[i]) {
...
src/bin/2sum.rs:3:1: 15:2 help: run `rustc --explain E0269` to see a detailed explanation
error: aborting due to previous error
是如何發生的有沒有錯誤?我該如何解決這個問題?
感謝
你可以讓所有的返回路徑返回一個值,在這種情況下,通過移除後'分號[0usize,0usize]' –
你「跑'rustc --explain E0269'看到一個詳細的解釋」爲編譯器提示? – Shepmaster
您可能會對[如何從HashMap中高效查找並插入HashMap]感興趣?(http://stackoverflow.com/q/28512394/155423)。 – Shepmaster