rust - Error: not all control paths return a value [E0269] -
i newbie of rust. here code find indices of 2 numbers such add specific target.
use std::collections::hashmap; fn two_sum(nums: &[i32], target: i32) -> [usize;2] { let mut map: hashmap<i32, usize> = hashmap::new(); 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]); }
i got error below
src/bin/2sum.rs:3:1: 15:2 error: not control paths return 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 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` see detailed explanation error: aborting due previous error
how happened there? how can solve problem?
thanks
you can remove semicolon after [0usize, 0usize]
(this idiomatic) or add return [0usize, 0usize]
.
to improve code can return option
. also, in case, better return tuple.
use std::collections::hashmap; fn two_sum(nums: &[i32], target: i32) -> option<(usize, usize)> { let mut map: hashmap<i32, usize> = hashmap::new(); 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); }
Comments
Post a Comment