注意:这个问题是在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 Struct<T>
where
T: Fn(&[u8]),
{
func: T,
}
impl<T> Struct<T>
where
T: Fn(&[u8]),
{
fn new() -> Struct<T> {
// this doesn't work
Struct { func: |msg| {} }
}
}
fn main() {
// this works
let s = Struct { func: |msg| {} };
}
Run Code Online (Sandbox Code Playgroud)
错误是
struct Struct<T>
where
T: Fn(&[u8]),
{
func: T,
}
impl<T> Struct<T>
where
T: Fn(&[u8]),
{
fn new() -> Struct<T> {
// this doesn't work
Struct { func: |msg| {} …
Run Code Online (Sandbox Code Playgroud)