jan
jan

Reputation: 143

Type Matching with a Tuple + Option/Some

I have been working on a Rust project for quite some time to learn rust and have hit a blocker that I have been working at for quite some time and not sure if it is possible to do in rust.

Main Goal
I want to be able to compare a tuple (x, y) with another tuple but have the expression evaluate to true if one of the values (in the same spot) match. so for example.

(x, y) == (a, y) = True
(x, z) == (z, x) = False
(x, z) == (x, b) = True

What Ive tried
I know that doing a match statement is the most straight forward way of doing this but I am passing this tuple into a third party function that is using this tuple to query a Map.

So I have tried using Option, and wrapping the values with Some and trying to do things like

(Some(_), Some(a)) == (Some(g), Some(a)) = Want this to equal true.

But it has not worked.

Is what I am trying to do possible in rust? what could I do to try to do this? Thank you so much for your time.

EDIT:
To make this more clear, this is the function that is using this tuple.

let entries_data = ENTRIES.may_load(deps.storage, (<<<anything>>>, address));

This tuple is being used to query a Map and I want to be able to query with a tuple that allows one of it's contents be anything (so it only matches to one item in the tuple).

Upvotes: 0

Views: 1129

Answers (2)

Campbell He
Campbell He

Reputation: 515

You can create a new type and implement PartialEq for it.

Maybe something like this:

struct MyTuple<T: PartialEq>(pub T, pub T);

impl<T: PartialEq> PartialEq for MyTuple<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0 || self.1 == other.1
    }
}

impl<T: PartialEq> Eq for MyTuple<T> {}

fn main() {
    let a = MyTuple(1, 2);
    let b = MyTuple(1, 3);
    let c = MyTuple(4, 2);
    let d = MyTuple(3, 1);
    let e = MyTuple(1, 5);
    
    println!("(1, 2) == (4, 2) : {}", a == c);
    println!("(1, 3) == (3, 1) : {}", b == d);
    println!("(1, 3) == (1, 5) : {}", b == e);
    // (1, 2) == (4, 2) : true
    // (1, 3) == (3, 1) : false
    // (1, 3) == (1, 5) : true
}

example in rust playground

Upvotes: 0

Chayim Friedman
Chayim Friedman

Reputation: 70940

Rust match can only match against static patterns. You cannot match against a variable.

The correct way is a simple if:

if a.0 == b.0 || a.1 == b.1 { ... }

Upvotes: 2

Related Questions