小编Ale*_*ndr的帖子

如何从特征对象获取对具体类型的引用?

如何获得Box<B>&B&Box<B>a在此代码变量:

trait A {}

struct B;
impl A for B {}

fn main() {
    let mut a: Box<dyn A> = Box::new(B);
    let b = a as Box<B>;
}
Run Code Online (Sandbox Code Playgroud)

此代码返回错误:

error[E0605]: non-primitive cast: `std::boxed::Box<dyn A>` as `std::boxed::Box<B>`
 --> src/main.rs:8:13
  |
8 |     let b = a as Box<B>;
  |             ^^^^^^^^^^^
  |
  = note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
Run Code Online (Sandbox Code Playgroud)

traits rust

38
推荐指数
2
解决办法
9184
查看次数

在文本文件中添加新行的最佳变体是什么?

我正在使用此代码将新行附加到文件的末尾:

let text = "New line".to_string();

let mut option = OpenOptions::new();
option.read(true);
option.write(true);
option.create(true);

match option.open("foo.txt") {
    Err(e) => {
        println!("Error");
    }
    Ok(mut f) => {
        println!("File opened");
        let size = f.seek(SeekFrom::End(0)).unwrap();
        let n_text = match size {
            0 => text.clone(),
            _ => format!("\n{}", text),
        };
        match f.write_all(n_text.as_bytes()) {
            Err(e) => {
                println!("Write error");
            }
            Ok(_) => {
                println!("Write success");
            }
        }

        f.sync_all();
    }
}
Run Code Online (Sandbox Code Playgroud)

它有效,但我认为这太难了.我找到了option.append(true);,但如果我使用它而不是option.write(true);我得到"写错误".

file-io rust

15
推荐指数
1
解决办法
6463
查看次数

标签 统计

rust ×2

file-io ×1

traits ×1