gpt4 book ai didi

rust - 如何返回一个值和对该值的一部分的引用?

转载 作者:行者123 更新时间:2023-11-29 08:28:37 24 4
gpt4 key购买 nike

<分区>

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

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`

有什么方法可以同时返回 connstate 还是我只能返回 conn

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com