【问题标题】:Store any type in a struct field将任何类型存储在结构字段中
【发布时间】:2018-01-15 07:26:34
【问题描述】:

我正在编写如下代码:

use std::cell::RefCell;

struct CallbackWithArgs<T> {
    callback: Box<Fn(&mut T) -> ()>,
    arg: RefCell<T>,
}

struct S {
    args: CallbackWithArgs<_>,
}

编译器出错:

error[E0121]: the type placeholder `_` is not allowed within types on item signatures
 --> src/main.rs:9:28
  |
9 |     args: CallbackWithArgs<_>,
  |                            ^ not allowed in type signatures

这样做的正确方法是什么?

【问题讨论】:

  • 请同时添加编译错误。
  • "那么有人能告诉我正确的方法吗?"这是什么”?你想做什么?
  • 你为什么不让S泛型来允许任何类型?
  • 编译器错误类似于expect std::any::Any + 'static, found std::any::Any``。因此,在我正确设置生命周期后,此错误已得到修复。我认为问题已经消失了。但是,对于泛型类型声明中生命周期和特征声明的组合,我仍然有些困惑。

标签: rust


【解决方案1】:

你不能在结构声明中使用_;编译器需要在编译时知道结构体的大小。

如果您希望类型是通用的,您可以向 S 添加类型参数,就像您对 CallbackWithArgs 所做的那样:

struct CallbackWithArgs<T> {
    callback: Box<Fn(&mut T) -> ()>,
    arg: RefCell<T>,
}

struct S<T> {
    args: CallbackWithArgs<T>,
}

Playground Link

有关_的解释,请参阅What is Vec<_>?

【讨论】:

  • 是的,我知道我不能在那个地方使用_。我只是想表达Any的想法。还是谢谢。
猜你喜欢
  • 2012-04-06
  • 1970-01-01
  • 2021-08-09
  • 2019-12-18
  • 1970-01-01
  • 2016-01-21
  • 2019-10-21
  • 1970-01-01
  • 2012-07-15
相关资源
最近更新 更多