相关疑难解决方法(0)

内部可变性如何用于缓存行为?

我正在尝试创建一个structPath并按需从指定的路径加载图像。这是我到目前为止的内容:

extern crate image;

use std::cell::{RefCell};
use std::path::{Path};
use image::{DynamicImage};

pub struct ImageCell<'a> {
    image: RefCell<Option<DynamicImage>>,
    image_path: &'a Path, 
}

impl<'a> ImageCell<'a> {
    pub fn new<P: AsRef<Path>>(image_path: &'a P) -> ImageCell<'a>{
        ImageCell { image: RefCell::new(None), image_path: image_path.as_ref() }
    }

    //copied from https://doc.rust-lang.org/nightly/std/cell/index.html#implementation-details-of-logically-immutable-methods
    pub fn get_image(&self) -> &DynamicImage {
        {
            let mut cache = self.image.borrow_mut();
            if cache.is_some() {
                return cache.as_ref().unwrap(); //Error here
            }

            let image = image::open(self.image_path).unwrap();
            *cache = Some(image);
        }

        self.get_image()
    } 
}
Run Code Online (Sandbox Code Playgroud)

无法编译:

src/image_generation.rs:34:24: 34:29 …
Run Code Online (Sandbox Code Playgroud)

mutability rust

5
推荐指数
1
解决办法
545
查看次数

Read::read_exact 不填充缓冲区

我有以下代码:

use std::io::{Cursor, BufReader, Read};

fn main() {
    let string = String::from("Cello");
    let bytes = string.as_bytes();
    let cursor = Cursor::new(bytes);
    let mut reader = BufReader::new(cursor);
    let mut buf: Vec<u8> = Vec::with_capacity(4);
    assert_eq!(4, buf.capacity());
    reader.read_exact(&mut buf);
    assert_eq!(4, buf.len()); //thread 'main' panicked at 'assertion failed: `(left == right)`
                              //left: `4`, right: `0`'
}
Run Code Online (Sandbox Code Playgroud)

根据std::io::read_exact的文档,它将“读取填充 buf 所需的确切字节数”。但在这种情况下,尽管有 4 个字节的容量,但没有字节被读入 vec。这是怎么回事?

io rust vec

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

标签 统计

rust ×2

io ×1

mutability ×1

vec ×1