rust - 传递初始化的虚拟 &str 以便它可以由函数填充

标签 rust

我的程序初始化一个变量“mag”,然后将它传递给一个函数,根据一个int修改它。

let n = some_number;
let m = "";
x = foo(n, m);

fn foo(n: u64, mut m: &str) -> &str {
    if n == 0 {
        m = "asdf";
    } else {
        m = "qwerty";
    return mag;
}

但是我收到一个编译器警告,说 mag 从未被阅读过。我无法返回在函数内部创建的变量,所以我必须在外部初始化 mag。有更好的方法吗?

最佳答案

您不需要四处传递引用,您可以毫无问题地在函数外部传递局部变量的所有权。 String 也可以解引用为 &str 如果你绝对需要的话:

fn main() -> std::io::Result<()> {
    let n = 55;
    let x = foo(n);

    match &x[..] {
        "querty" => println!("Yep it was qwerty!"),
        _ => println!("Nope it wasn't qwerty :(")
    };

    Ok(())
}

fn foo(n: u64) -> String {
    if n == 0 {
        String::from("asdf")
    } else {
        String::from("querty")
    }
}

打印“是的,它是 qwerty!”。

Playground :https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d7830c124171ab8a3c64f55a5c89590f

根据您的评论进行了编辑以包含匹配项。

关于rust - 传递初始化的虚拟 &str 以便它可以由函数填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55931018/

相关文章:

rust - 如何包装动态类型流以方便 API?

go - 在 Golang 和 Rust 上使用 Messagepack 编码时的输出不同

vector - 是否可以使用迭代器将向量分成 10 个一组?

module - 在 Rust 2018 中使用模块时如何解决错误 "no module in the root"?

rust - 将Box与nom解析器一起使用时出现神秘错误 “one type is more general than the other”

xml - 解析文件返回错误 "thread ' main' paniced"

rust - 当每晚使用 `cargo run` 和 Rust 1.9 运行时,从 stdin 读取不会读取任何数据

postgresql - 不能使用 UUID 作为主键:Uuid:diesel::Expression 不满足

closures - 使用线程时的生命周期问题

rust - 无法在文件中找到字符串的位置,因为在移动后使用了 BufReader