如何 return 一个值和对该值的一部分的引用?

How to return a value and a reference to a portion of that value?

我在尝试学习 Rust 的同时尝试使用 some xcb bindings

conn.get_setup()只是借用了一个不可变引用;函数调用结束后那个借用不就结束了吗?

use std::error::Error; 
use std::convert::From;

pub struct State<'a> {
    conn: xcb::Connection,
    screen: xcb::Screen<'a>,
}

impl<'a> State<'a> {
    pub fn new() -> Result<State<'a>, Box<dyn Error>> {
        let (conn, _) = xcb::Connection::connect(None)?;
        let screen = conn.get_setup().roots().next().ok_or::<Box<dyn Error>>(From::from("Couldn't get screen"))?;
        Ok(State{conn: conn, screen:screen})
    }
}

编译器给我

error[E0515]: cannot return value referencing local variable `conn`
  --> /.../src/lib.rs:16:4
   |
15 |             let screen = conn.get_setup().roots().next().ok_or::<Box<dyn Error>>(From::from("Couldn't get screen"))?;
   |                          ---- `conn` is borrowed here
16 |             Ok(State{conn: conn, screen:screen})
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function

error[E0505]: cannot move out of `conn` because it is borrowed
  --> /.../src/lib.rs:16:19
   |
12 |     impl<'a> State<'a> {
   |          -- lifetime `'a` defined here
...
15 |             let screen = conn.get_setup().roots().next().ok_or::<Box<dyn Error>>(From::from("Couldn't get screen"))?;
   |                          ---- borrow of `conn` occurs here
16 |             Ok(State{conn: conn, screen:screen})
   |             ---------------^^^^-----------------
   |             |              |
   |             |              move out of `conn` occurs here
   |             returning this value requires that `conn` is borrowed for `'a`

有什么方法可以 return 同时 connstate 还是我只限于 conn

如果您这样做,将会出现 use after free 错误:

  1. conn 已创建,没有附加生命周期
  2. 我们为 'a 借用 conn,这本身是不可能的,因为我可以说 following:
State::<'static>::new()
  1. 我们将 conn 移出函数,使对它的任何引用无效。

因此,除非您正在使用的库中有其他方法可以实现此目的,否则这不会按原样工作。它的另一个名称是自引用结构,因此您可能想要研究一下为什么它在 rust 中不起作用。