我想写这个结构:
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) 我想定义一个类型,包括Rc<Fn(T)>,T 不要求Clone特性,例如代码:
use std::rc::Rc;
struct X;
#[derive(Clone)]
struct Test<T> {
a: Rc<Fn(T)>
}
fn main() {
let t: Test<X> = Test {
a: Rc::new(|x| {})
};
let a = t.clone();
}
Run Code Online (Sandbox Code Playgroud)
无法编译,错误信息是:
test.rs:16:15: 16:22 note: the method `clone` exists but the following trait bounds were not satisfied: `X : core::clone::Clone`, `X : core::clone::Clone`
test.rs:16:15: 16:22 help: items from traits can only be used if the trait is implemented and in scope; the following trait …Run Code Online (Sandbox Code Playgroud) rustc 1.0.0-夜间(be9bd7c93 2015-04-05)(建于2015-04-05)
extern crate rand;
fn test(a: isize) {
println!("{}", a);
}
fn main() {
test(rand::random() % 20)
}
Run Code Online (Sandbox Code Playgroud)
此代码在Rust beta之前编译,但现在它没有:
src/main.rs:8:10: 8:22 error: unable to infer enough type information about `_`; type annotations required [E0282]
src/main.rs:8 test(rand::random() % 20)
^~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
我必须编写这段代码来编译:
extern crate rand;
fn test(a: isize) {
println!("{}", a);
}
fn main() {
test(rand::random::<isize>() % 20)
}
Run Code Online (Sandbox Code Playgroud)
如何让编译器推断出类型?