How to Borrow variable multiple times for Logical Operator

How do we use a variable multiple times as ref for a logical operation? E.g, an OR statement?

let check:HashMap<i8, i8> = HashMap::new();
// insert some data into hashmap
if &check.contains_key(1) || &check.contains_key(3) {
    println!("YES!");

}

Sorry, new to rust, but trying to learn


Solution 1:

As others have said, you're not borrowing what you think you are, but the rules of rust mean you don't need to borrow like you are when calling a method of HashMap. This is simpler, and also I made it mutable so you could insert a value and see success, as well as a query failure.

use std::error::Error;
use std::collections::HashMap;

fn main() -> Result<(), Box<dyn Error>> {
    let mut check:HashMap<i8, i8> = HashMap::new();
    // insert some data into hashmap
    check.insert(1, 5);
    // Check for 1 or 3
    if check.contains_key(&1) || check.contains_key(&3) {
        println!("Contained a key of 1 OR 3!");
    }
    if check.contains_key(&3) {
        println!("Contained a key of 3!");
    }
    else
    {
        println!("Did not contain a key of 3!");
    }
    Ok(())
}

You don't need to specify & or & mut before a borrow for a method of a struct. For the arguments yes, but not the method itself, as there is no overloading in Rust (like in C++ or some other languages) and thus it's unambiguous which you call, so Rust does the work borrowing for you.

Link to the online rust playground for this example.