相关疑难解决方法(0)

为什么不鼓励接受对String(&String),Vec(&Vec)或Box(&Box)的引用作为函数参数?

我写了一些Rust代码&String作为参数:

fn awesome_greeting(name: &String) {
    println!("Wow, you are awesome, {}!", name);
}
Run Code Online (Sandbox Code Playgroud)

我还编写了代码来引用a VecBox:

fn total_price(prices: &Vec<i32>) -> i32 {
    prices.iter().sum()
}

fn is_even(value: &Box<i32>) -> bool {
    **value % 2 == 0
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到一些反馈意见,这样做并不是一个好主意.为什么不?

string reference rust borrowing

100
推荐指数
2
解决办法
5549
查看次数

有没有办法返回对函数中创建的变量的引用?

我想编写一个程序,分两步编写一个文件.在程序运行之前,该文件可能不存在.文件名是固定的.

问题是OpenOptions.new().write()可能会失败.在这种情况下,我想调用自定义函数trycreate().我们的想法是创建文件而不是打开它并返回一个句柄.由于文件名是固定的,trycreate()没有参数,我不能设置返回值的生命周期.

我该如何解决这个问题?

use std::io::Write;
use std::fs::OpenOptions;
use std::path::Path;

fn trycreate() -> &OpenOptions {
    let f = OpenOptions::new().write(true).open("foo.txt");
    let mut f = match f {
        Ok(file)  => file,
        Err(_)  => panic!("ERR"),
    };
    f
}

fn main() {
    {
        let f = OpenOptions::new().write(true).open(b"foo.txt");
        let mut f = match f {
            Ok(file)  => file,
            Err(_)  => trycreate("foo.txt"),
        };
        let buf = b"test1\n";
        let _ret = f.write(buf).unwrap();
    }
    println!("50%");
    {
        let f = OpenOptions::new().append(true).open("foo.txt");
        let mut f …
Run Code Online (Sandbox Code Playgroud)

reference lifetime rust

31
推荐指数
4
解决办法
1万
查看次数

是否允许多态变量?

我有各种结构,都实现相同的特征.我想在某些条件下进行分支,在运行时决定实例化哪些结构.然后,无论我遵循哪个分支,我都想从该特征中调用方法.

这可能在Rust吗?我希望实现类似下面的内容(不编译):

trait Barks {
    fn bark(&self);
}

struct Dog;

impl Barks for Dog {
    fn bark(&self) {
        println!("Yip.");
    }
}

struct Wolf;

impl Barks for Wolf {
    fn bark(&self) {
        println!("WOOF!");
    }
}

fn main() {
    let animal: Barks;
    if 1 == 2 {
        animal = Dog;
    } else {
        animal = Wolf;
    }
    animal.bark();
}
Run Code Online (Sandbox Code Playgroud)

rust

14
推荐指数
3
解决办法
655
查看次数

我如何制作格式!从条件表达式返回 &amp;str?

我遇到了这个问题format!,据我所知,在一个没有锚定到任何东西的模式中创建一个临时值。

let x = 42;
let category = match x {
    0...9 => "Between 0 and 9",
    number @ 10 => format!("It's a {}!", number).as_str(),
    _ if x < 0 => "Negative",
    _ => "Something else",
};

println!("{}", category);
Run Code Online (Sandbox Code Playgroud)

在这段代码中, 的类型category是 a &str,它通过返回一个像 的文字来满足"Between 0 and 9"。如果我想使用 将匹配的值格式化为切片as_str(),则会出现错误:

let x = 42;
let category = match x {
    0...9 => "Between 0 and 9",
    number @ 10 => format!("It's a {}!", …
Run Code Online (Sandbox Code Playgroud)

string scope temporary lifetime rust

8
推荐指数
1
解决办法
2502
查看次数

标签 统计

rust ×4

lifetime ×2

reference ×2

string ×2

borrowing ×1

scope ×1

temporary ×1