我是Rust的新手。以下是查找两个数字的索引的代码,以便它们相加到特定目标。
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
那边怎么了?我该如何解决这个问题呢?
由于
答案 0 :(得分:3)
您可以在[0usize, 0usize]
(this is idiomatic)之后删除分号或添加return [0usize, 0usize]
。
要改进代码,您可以返回Option
。此外,在这种情况下,最好返回一个元组。
use std::collections::HashMap;
fn two_sum(nums: &[i32], target: i32) -> Option<(usize, usize)> {
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 Some((seen, i)),
_ => map.insert(want, i),
};
}
None
}
fn main() {
let nums = [1, 3, 7, 4];
let res = two_sum(&nums, 10);
println!("{:?}", res);
}