以下Rust代码编译并运行没有任何问题.
fn main() {
let text = "abc";
println!("{}", text.split(' ').take(2).count());
}
Run Code Online (Sandbox Code Playgroud)
在那之后,我尝试了类似的东西....但它没有编译
fn main() {
let text = "word1 word2 word3";
println!("{}", to_words(text).take(2).count());
}
fn to_words(text: &str) -> &Iterator<Item = &str> {
&(text.split(' '))
}
Run Code Online (Sandbox Code Playgroud)
主要问题是我不确定函数to_words()应该具有什么返回类型.编译器说:
error[E0599]: no method named `count` found for type `std::iter::Take<std::iter::Iterator<Item=&str>>` in the current scope
--> src/main.rs:3:43
|
3 | println!("{}", to_words(text).take(2).count());
| ^^^^^
|
= note: the method `count` exists but the following trait bounds were not satisfied:
`std::iter::Iterator<Item=&str> : std::marker::Sized`
`std::iter::Take<std::iter::Iterator<Item=&str>> …Run Code Online (Sandbox Code Playgroud) 注意:这个问题是在Rust第一次稳定发布之前提出的.之后发生了很多变化,函数中使用的语法甚至不再有效.尽管如此,Shepmaster的答案仍然非常出色,这使得这个问题值得保留.
最后,未装箱的封闭装置着陆了,所以我正在试验它们,看看你能做些什么.
我有这个简单的功能:
fn make_adder(a: int, b: int) -> || -> int {
|| a + b
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到了一个missing lifetime specifier [E0106]错误.我试图通过将返回类型更改为修复此问题||: 'static -> int,但后来又出现了另一个错误cannot infer an appropriate lifetime due to conflicting requirements.
如果我理解正确,关闭是未装箱的,所以它拥有a和b.我觉得它需要一辈子似乎很奇怪.我怎样才能解决这个问题?
我试图将活塞纹理存储在结构中.
struct TextureFactory<R> where R: gfx::Resources {
block_textures: Vec<Rc<Texture<R>>>,
}
impl<R> TextureFactory<R> where R: gfx::Resources {
fn new(window: PistonWindow) -> Self {
let texture = Rc::new(gfx_texture::Texture::from_path(
&mut *window.factory.borrow_mut(),
"assets/element_red_square.png",
Flip::None, &TextureSettings::new()
).unwrap());
let block_textures = Vec::new();
block_textures.push(texture);
TextureFactory {
block_textures: block_textures,
}
}
}
Run Code Online (Sandbox Code Playgroud)
这不编译:
src/main.rs:37:9: 39:10 error: mismatched types:
expected `TextureFactory<R>`,
found `TextureFactory<gfx_device_gl::Resources>`
(expected type parameter,
found enum `gfx_device_gl::Resources`)
Run Code Online (Sandbox Code Playgroud)
gfx_device_gl::Resources gfx::Resources虽然实现(我认为它只是设备特定的实现.)我实际上并不关心这是什么类型,但我需要知道,以便我可以将它存储在结构中.
(我怀疑Rust的特征/特征:"预期'Foo <B>',发现'Foo <Foo2>'"是同一个问题,但我无法弄清楚如何将它应用到我的问题中.)
我有以下代码:
struct Helper<F1: Fn()> {
f: F1,
}
struct User<F2: Fn()> {
h: Helper<F2>,
}
fn new_user<F3: Fn()>() -> User<F3> {
User {
// error: expected type parameter, found closure
h: Helper { f: || {} },
}
}
fn main(){}
Run Code Online (Sandbox Code Playgroud)
所以User需要一个Helper<F1>由 指定的 F1 类型User,在这种情况下是由中的闭包new_user。
此代码编译失败与错误expected type parameter, found closure在new_user。至于我已经明白(例如见这个链接),这是因为约束类型参数F3上new_user被调用者指定(或签名也许?),因此,虽然关闭实现Fn()特质,它不能限制类型参数 F3 以匹配闭包的类型。相反,它new_user应该适用于任何给定的F3,而这显然不会。
所以我的问题是:我该如何解决这个问题?有没有表达,我想的任何方式new_user …