我有一个值,我想在我自己的类型中存储该值以及对该值内部内容的引用:
struct Thing {
count: u32,
}
struct Combined<'a>(Thing, &'a u32);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing { count: 42 };
Combined(thing, &thing.count)
}
Run Code Online (Sandbox Code Playgroud)
有时候,我有一个值,我想在同一个结构中存储该值和对该值的引用:
struct Combined<'a>(Thing, &'a Thing);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing::new();
Combined(thing, &thing)
}
Run Code Online (Sandbox Code Playgroud)
有时,我甚至没有参考该值,我得到同样的错误:
struct Combined<'a>(Parent, Child<'a>);
fn make_combined<'a>() -> Combined<'a> {
let parent = Parent::new();
let child = parent.child();
Combined(parent, child)
}
Run Code Online (Sandbox Code Playgroud)
在每种情况下,我都会收到一个错误,即其中一个值"活不够长".这个错误是什么意思?
我对Rust非常感兴趣,现在我开始用语言开展我的第一个非平凡的项目.我仍然在完全理解借贷和终身概念方面遇到一些麻烦.
该应用程序是一个逻辑门模拟器,其中组件是递归定义的(就其他组件及其互连而言).
我目前的计划是通过让Component组件拥有一个Components(它的子组件)向量和一个Nets向量来描述这些组件之间的相互连接,就像在C++中一样实现它:
pub struct Pin {
name: String
}
pub struct Net<'a> {
nodes: Vec<(&'a Component<'a>,&'a Pin)>
}
pub struct Component<'a> {
sub_components: Vec<Box<Component<'a>>>,
in_pins: Vec<Pin>,
out_pins: Vec<Pin>,
netlist: Vec<Net<'a>>
}
impl<'a> Component<'a> {
pub fn new() -> Component<'a> {
...
}
pub fn add_subcomponent( & mut self, comp: Component<'a> ) {
// -> &Box<Component<'a>> ??
....
}
}
Run Code Online (Sandbox Code Playgroud)
在C++中,Net很容易实现为指向组件的指针数组,但我不确定在Rust中执行此操作的最佳方法,我想我应该使用借来的指针?或者,还有更好的方法?
请考虑以下主要内容:
fn main() {
let sub1 = Component::new();
let sub2 = Component::new();
let circuit = Component::new();
circuit.add_subcomponent( sub1 ); …Run Code Online (Sandbox Code Playgroud) 我正在研究我的第一个Rust程序,并且与Rust所有权语义相冲突.我声明了一个struct将封装SQLite数据库连接,以便它维护一个Connection成员.出于性能原因,我还想保留一个准备好的语句,由Statement类型表示.这是我的代码的简化版本:
extern crate rusqlite; // 0.14.0
use rusqlite::{Connection, Statement};
pub struct Foo<'a> {
conn: Connection,
statement: Statement<'a>,
}
impl<'a> Foo<'a> {
pub fn new() -> Foo<'a> {
let conn = Connection::open(&":memory:").unwrap();
let statement = conn
.prepare("INSERT INTO Foo(name, hash) VALUES($1, $2)")
.unwrap();
Foo { conn, statement }
}
}
Run Code Online (Sandbox Code Playgroud)
我试图通过将conn变量的所有权存储在成员中来将变量的所有权转移给被调用者Foo,但是当我尝试编译此代码时,它失败了:
error[E0597]: `conn` does not live long enough
--> src/main.rs:13:25
|
13 | let statement = conn
| ^^^^ borrowed value …Run Code Online (Sandbox Code Playgroud) 在我的代码中,我有一个相互递归的树结构,如下所示:
enum Child<'r> {
A(&'r Node<'r>),
B,
C
}
struct Node<'r> {
children : [&'r Child<'r>,..25]
}
impl <'r>Node<'r> {
fn new() -> Node {
Node {
children : [&B,..25]
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它不按原样编译.修改它的最佳方法是什么?