我有一个值,我想在我自己的类型中存储该值以及对该值内部内容的引用:
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文档,并遇到了以下示例和声明
使用return作为函数的最后一行有效,但被认为是糟糕的样式:
fn foo(x: i32) -> i32 {
if x < 5 { return x; }
return x + 1;
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以写上面的内容
fn foo(x: i32) -> i32 {
if x < 5 { return x; }
x + 1
}
Run Code Online (Sandbox Code Playgroud)
但我更倾向于写前者,因为这更直观.我确实理解函数返回值应该用作表达式,以便后面有效但是为什么不鼓励前者呢?