0
votes

I am trying to use the rmp_rpc Rust libary to make a server that accepts commands from a client that is written in Python. I am modifying this example to reach my goal.

How can I handle an argument of varying type (integer/string/boolean) into a match statement without getting a "mismatched types; expected i32, found enum 'rmp_rpc::Value'" error? For each method the params types might be different.

fn handle_request(&mut self, method: &str, params: &[Value]) -> Self::RequestFuture {
        match method {
            "sum" => Methods::sum(params[0], params[1]),
            "draw" => Methods::draw(params),
            "conc" => Methods::concatenate(params[0], params[1])
        }
2
Please review how to create a minimal reproducible example and then edit your question to include it. We cannot tell what crates, types, traits, fields, etc. are present in the code. Ideally, produce something that reproduces your error on the Rust Playground. There are Rust-specific MCVE tips as well. - Shepmaster

2 Answers

0
votes

You need to either perform your type checking here at the call site, or defer type-checking to the callee (the Echo::<whatever> methods).

At the call site:

match method {
    "sum" => Echo::sum(params[0].as_u64().expect("expected u64"), params[1].as_u64().expect("expected u64")),
    "draw" => Echo::draw(params), // <-- this must continue to be passed as &[Value]
    "concatenate => Echo::conc(params[0].as_str().expect("expected str"), params[1].as_str().expect("expected str"))
}

In the callee:

impl Echo {
    pub fn sum(v1: Value, v2: Value) -> u64 {
        let v1 = v1.as_u64().expect("expected u64");
        let v2 = v2.as_u64().expect("expected u64");

        v1 + v2
    }
}

This is based on the documentation I could find available.

0
votes

What I did according to Simon was
match method { "sum" => Methods::sum(params[0].as_u64().expect("expected u64"), params[1].as_u64().expect("expected u64")), "conc" => Methods::concatenate(params[0].as_str().expect("expected str"), params[1].as_str().expect("expected str")), "draw" => Methods::draw(params), _ => Err("invalid argument".into()) }
but also fix each function's output to a Result<'Value, Value> in order to avoid incompatible type error