匹配字符串:不能移出借用内容 [英] Matching String: cannot move out of borrowed content

查看:39
本文介绍了匹配字符串:不能移出借用内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

req.url.fragment 是一个可选的 String.如果它有一个值,我想将该值复制到 fragment 中,否则我想分配一个空字符串.我不断收到无法移出借用内容的错误.

req.url.fragment is an optional String. If it has a value, I want to copy that value into fragment, otherwise I want to assign an empty string. I keep getting the error that I cannot move out of borrowed content.

我该如何解决这个问题?

How do I resolve this?

fn fb_token(req: &mut Request) -> IronResult<Response> {
    let fragment = match req.url.fragment {
        Some(fragment) => fragment,
        None => "".to_string(),
    };

    Ok(Response::with((status::Ok, fragment)))
}

推荐答案

这取决于你想对结构中的现有字符串做什么.

It depends on what you want to do with the existing string in the structure.

let fragment = match req.url.fragment {
    Some(fragment) => fragment,
    None => "".to_string(),
};

在这段代码中,您正在移动req.url.fragment 中的字符串,但这会使其处于未定义状态.这是一件坏事,而 Rust 会阻止您这样做!

In this code, you are moving the String out of req.url.fragment, but that would leave it in an undefined state. That's a bad thing, and Rust prevents you from doing that!

如错误消息所述:

为了防止移动,使用ref fragmentref mut fragment通过引用捕获值

to prevent the move, use ref fragment or ref mut fragment to capture value by reference

如果你想把字符串留在原处并返回一个副本,那么你可以获取一个引用然后克隆它:

If you want to leave the string where it is and return a copy, then you can take a reference and then clone it:

let fragment = match req.url {
    Some(ref fragment) => fragment.clone(),
    None => "".to_string()
};

如果要将现有字符串保留为None,则可以使用take:

If you want to leave the existing string as a None, then you can use take:

let fragment = match req.url.take() {
    Some(fragment) => fragment,
    None => "".to_string()
};

更短的,你可以使用unwrap_or_else:

let fragment = req.url.take().unwrap_or_else(String::new);

这篇关于匹配字符串:不能移出借用内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆