相关疑难解决方法(0)

什么是非词汇生命?

Rust有一个与非词汇生命周期相关的RFC,已被批准在该语言中实现了很长时间.最近,Rust对此功能的支持有了很大改进,并且被认为是完整的.

我的问题是:非词汇生命究竟是什么?

lifetime rust lifetime-scoping

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

Rust如何提供移动语义?

锈语言网站索赔移动语义的语言的特征之一.但我无法看到Rust中如何实现移动语义.

Rust box是唯一使用移动语义的地方.

let x = Box::new(5);
let y: Box<i32> = x; // x is 'moved'
Run Code Online (Sandbox Code Playgroud)

上面的Rust代码可以用C++编写

auto x = std::make_unique<int>();
auto y = std::move(x); // Note the explicit move
Run Code Online (Sandbox Code Playgroud)

据我所知(如果我错了,请纠正我),

  • Rust根本没有构造函数,更不用说移动构造函数了.
  • 不支持右值参考.
  • 无法使用rvalue参数创建函数重载.

Rust如何提供移动语义?

move-semantics rust

37
推荐指数
3
解决办法
8225
查看次数

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

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

问题是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中使用struct的生命周期的正确方法是什么?

我想写这个结构:

struct A {
    b: B,
    c: C,
}

struct B {
    c: &C,
}

struct C;
Run Code Online (Sandbox Code Playgroud)

B.c应借A.c.

A ->
  b: B ->
    c: &C -- borrow from --+
                           |
  c: C  <------------------+
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的:struct C;

struct B<'b> {
    c: &'b C,
}

struct A<'a> {
    b: B<'a>,
    c: C,
}

impl<'a> A<'a> {
    fn new<'b>() -> A<'b> {
        let c = C;
        A {
            c: c,
            b: B { c: &c },
        }
    }
}

fn …
Run Code Online (Sandbox Code Playgroud)

lifetime rust

25
推荐指数
2
解决办法
2万
查看次数

如何初始化相互引用的struct字段

我目前想要使用GamerIterator 为活塞游戏定义一个结构:

pub struct MyGame<'a> {
    game_window: GameWindowGLFW,
    game_iter: GameIterator<'a, GameWindowGLFW>,
    //...
}
Run Code Online (Sandbox Code Playgroud)

GameIterator是在通用GameWindow和它的使用寿命.我想告诉编译器它与字段"game_window"/"整个结构"具有相同的生命周期,并省略了结构的生命周期.

我也很难初始化这个:

MyGame {
    game_window: GameWindowGLFW::new(GameWindowSettings {/*...*/},
    game_iter: GameIterator::new(&mut game_window, &game_iter_settings), // game_window cannot be used here
    //...
}
Run Code Online (Sandbox Code Playgroud)

我认为我可以通过使用Option<GameIterator<...>>和init()方法解决初始化问题,但我想避免这种情况,因为我可以保证game_iternew()完成后存在.

写这个的惯用方法是什么?

rust

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

由于需求冲突,无法推断autoref的适当生命周期

我在代码中遇到了特定功能的终生问题.我正在学习Rust和SDL的教程.该教程稍微陈旧,SDL库自编写以来已经发生了变化,所以我一直在跟进,同时也适应最新版本的Rust-SDL.

终身问题在于这个功能:

pub fn ttf_str_sprite(&mut self, text: &str, font_path: &'static str, size: i32, color: Color) -> Option<Sprite> {
    if let Some(font) = self.cached_fonts.get(&(font_path, size)) {
        return font.render(text).blended(color).ok()
            .and_then(|surface| self.renderer.create_texture_from_surface(&surface).ok())
            .map(Sprite::new)
    }
    //::sdl2_ttf::Font::from_file(Path::new(font_path), size).ok()
    self.ttf_context.load_font(Path::new(font_path), size as u16).ok()
        .and_then(|font| {
            self.cached_fonts.insert((font_path, size), font);
            self.ttf_str_sprite(text, font_path, size, color)
    })
}
Run Code Online (Sandbox Code Playgroud)

尤其是线路self.ttf_context.load_font(Path::new(font_path), size as u16).ok().上面的注释行是旧的SDL版本的字体加载方法.

error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> src\phi/mod.rs:57:26
   |
57 |         self.ttf_context.load_font(Path::new(font_path), size as u16).ok()
   |                          ^^^^^^^^^
   |
help: consider …
Run Code Online (Sandbox Code Playgroud)

sdl lifetime rust

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

如何返回对互斥锁下的值的子值的引用?

我有一个看起来像这样的结构:

pub struct MyStruct {
    data: Arc<Mutex<HashMap<i32, Vec<i32>>>>,
}
Run Code Online (Sandbox Code Playgroud)

我可以很容易地锁定互斥锁并查询底层HashMap:

let d = s.data.lock().unwrap();
let v = d.get(&1).unwrap();
println!("{:?}", v);
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个封装查询的方法,所以我写了这样的东西:

impl MyStruct {
    pub fn get_data_for(&self, i: &i32) -> &Vec<i32> {
        let d = self.data.lock().unwrap();
        d.get(i).unwrap()
    }
}
Run Code Online (Sandbox Code Playgroud)

这无法编译,因为我试图在以下情况下返回对数据的引用Mutex:

error: `d` does not live long enough
  --> <anon>:30:9
   |
30 |         d.get(i).unwrap()
   |         ^
   |
note: reference must be valid for the anonymous lifetime #1 defined on the block at 28:53...
  --> <anon>:28:54
   |
28 …
Run Code Online (Sandbox Code Playgroud)

rust

15
推荐指数
4
解决办法
1493
查看次数

新提出的Pin类型有哪些用例?

Pin不稳定的Rust中有一个新类型,RFC已经合并.据说传递引用时它被称为游戏改变者,但我不确定如何以及何时应该使用它.

任何人都可以用外行的话来解释它吗?

reference rust

14
推荐指数
2
解决办法
693
查看次数

我何时或为什么要在RwLock上使用Mutex?

当我读到的单证MutexRwLock,我看到区别如下:

  • Mutex 一次只能有一个读者或作者,
  • RwLock 一次可以有一个作家或多个读者.

当你这样说的时候,RwLock似乎总是更好(更少限制)Mutex,为什么我会使用它呢?

multithreading mutex readwritelock rust

13
推荐指数
2
解决办法
1633
查看次数

在Rust结构中使用自引用封装顺序初始化状态

我正在尝试定义一个结构,它可以充当一个Vec在以下内容中保存的迭代器RefCell:

use std::slice::Iter;
use std::cell::Ref;
use std::cell::RefCell;

struct HoldsVecInRefCell {
    vec_in_refcell: RefCell<Vec<i32>>,
}

// TODO: struct HoldsVecInRefCellIter implementing Iterator ...

impl HoldsVecInRefCell {
    fn new() -> HoldsVecInRefCell {
        HoldsVecInRefCell { vec_in_refcell: RefCell::new(Vec::new()) }
    }

    fn add_int(&self, i: i32) {
        self.vec_in_refcell.borrow_mut().push(i);
    }

    fn iter(&self) -> HoldsVecInRefCellIter {
        // TODO ...
    }
}

fn main() {
    let holds_vec = HoldsVecInRefCell::new();
    holds_vec.add_int(1);
    holds_vec.add_int(2);
    holds_vec.add_int(3);

    let mut vec_iter = holds_vec.iter();  // Under the hood: run-time borrow check

    for i in …
Run Code Online (Sandbox Code Playgroud)

rust

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