It’s a good idea to solve the problem of leetCode’s algorithm, but I think it’s quite troublesome to write in Rust. . Failure to notice some details leads to various compilation errors, emmmmmm

The following code has been passed leetcode

use std::collections::HashMap;

impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) - >Vec<i32> {
        let mut v:Vec<i32> = Vec::new();
        let mut temp = 0;
        let mut sub = 0;
        let mut map:HashMap<i32.i32> = HashMap::new();
        
        for item in &nums{
            temp = target - item;
            
            if map.contains_key(&temp){
            
                match map.get(&temp){
                    Some(value) => {
                        v.push(*value);
                    }
                    
                    None => {
                        
                    }
                }
                v.push(sub);
                
                break;
            }else{
                map.insert(*item,sub);
            }
            
            sub += 1;
            
        }
        
        v
    }
}
Copy the code

As A result, various problems emerged on Rust Playground (rust-lang.org). Of course, the most deadly one was the usage of HashMap, such as get method. I originally thought that it was just like JS, Get directly retrieves the value of a key,

if map.contains_key(&temp){
        v.push(map.get(&temp));
        v.push(sub);
            
        break;
}else{
        map.insert(item,sub);
}
Copy the code

But keep reporting type error

Then I tried to solve the problem, and when I looked at the information, I found the problemRust Collections – Rust Basics tutorials – Simple Tutorials, Simple Programming (twle.cn)The get method returns a structure, and the problem is solved.