The following function has an error that it returns a value referencing data owned by the current function.
The thing is, the code that is commented out compiles (and runs) just fine — I am just trying to refactor the commended out code to the method get_str()
.
fn read_ping_query<'a>(dict: HashMap<&'a str, Bencode<'a>>) -> Result<RPC<'a>> {
let arg = match dict.get("a") {
Some(Bencode::Dict(arg)) => arg,
_ => anyhow::bail!("read_ping_query: arguments not found"),
};
// let node_id = match arg.get("id") {
// Some(Bencode::Str(node_id)) => node_id,
// _ => anyhow::bail!("read_ping_query: node_id not found"),
// };
let node_id = arg.get_str("id").context("read_ping_query: no node_id found")?;
Ok(RPC::PingQuery { node_id })
}
Here is the error message:
error[E0515]: cannot return value referencing function parameter `dict`
--> src/rpc.rs:39:5
|
26 | let arg = match dict.get("a") {
| ------------- `dict` is borrowed here
...
39 | Ok(RPC::PingQuery { node_id })
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
Basically, the commented out code is a pattern I am using repeatably, so I tried to refactor it into a custom trait method get_str()
.
#[derive(Debug, PartialEq)]
pub enum Bencode<'a> {
Int(i64),
Str(&'a [u8]),
List(Vec<Bencode<'a>>),
Dict(HashMap<&'a str, Bencode<'a>>),
}
pub trait FromBencode {
fn get_str(&self, key: &str) -> Option<&[u8]>;
}
impl<'a> FromBencode for HashMap<&str, Bencode<'a>> {
fn get_str(&self, key: &str) -> Option<&[u8]> {
match self.get(key) {
Some(Bencode::Str(value)) => Some(value),
_ => None,
}
}
}
As far as I can tell, what I am doing in the method get_str()
is equivalent to code in the comments (that works fine).
Any help understanding why this get_str()
method doesn't work is appreciated!