- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
根据 this answer至 this questions我需要执行以下操作以返回 Trait
的实例:
trait Shader {}
struct MyShader;
impl Shader for MyShader {}
struct GraphicsContext;
impl GraphicsContext {
fn create_shader(&self) -> impl Shader {
let shader = MyShader;
shader
}
}
但是当我尝试这样做时:
pub trait Component { }
struct Kind {}
struct Location {}
impl Component for Kind {}
impl Component for Location {}
pub fn get(comp_name: &String) -> impl Component {
match comp_name.as_ref() {
"kind" => Kind,
"location" => Location
}
}
我只是得到错误:
error[E0423]: expected value, found struct
Kind
--> src/main.rs:17:24|
17 | "kind" => Kind,
| ^^^^ did you mean `Kind { /* fields */ }`?error[E0423]: expected value, found struct
Location
--> src/main.rs:18:24|
18 | "location" => Location
| ^^^^^^^^ did you mean `Location { /* fields */ >}`?
最佳答案
那个impl Component
因为返回类型基本上是 T where T: Component
, 其中T
由函数本身而不是调用者选择。
T
可以是Kind
, T
可以是Location
,但是 T
不能同时兼顾。
两种解决方案:
动态地:返回 Box<dyn Component>
并返回 Box::new(Kind{})
或 Box::new(Location{})
.缺点是它会导致堆分配。
静态地,通过返回 enum
:
enum KindOrLocation {
Kind(Kind),
Location(Location),
}
使它可以用作 Component
, 你可以实现 Deref<Target = dyn Component>
:
impl Deref for KindOrLocation {
type Target = dyn Component + 'static;
fn deref(&self) -> &Self::Target {
match self {
KindOrLocation::Kind(x) => x,
KindOrLocation::Location(x) => x,
}
}
}
这里的缺点是您必须编写此样板代码。
顺便说一句:
{}
定义结构喜欢struct Kind {}
,您通过编写 Kind{}
创建它的一个对象,不只是 Kind
._
你的比赛中的案例:_ => panic!()
什么的。&String
, 但取 &str
反而。然后它适用于两者 &String
和 &str
.关于Rust 不允许我从匹配中返回一个类型的实例,一直认为我正在尝试返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55540512/
我有一个在 Android 市场上相当流行的应用程序,它允许数以万计的用户按下一个按钮并向它发出语音命令。然后我就可以做很多不同的事情,比如给他们提供当前的天气预报等等...... 无论如何,我的应用
令人惊讶的是,标题基本上解释了它。我们有一个我们的客户制作的页面,我们正在重新创建该页面。 页面高度会一直增加,直到(我假设是这样)浏览器达到它的极限。我已经尝试过 Firebug 和 W3 验证器,
我是 react-native 的新手,试图创建我自己的组件,但它一直显示一个空屏幕。 这是我的组件代码 class BoxComponent extends Component { cons
我正在为我的 PHP 元素创建一个非常简单的博客,但遇到了一个简单的问题。我无法让我的页眉图像一直 float 。我有一个横幅,左边有一些文字,我有一个 1px 的切片,在可以选择的任何分辨率的宽度上
为什么我可以在另一个 Controller 的 View 中访问一个 Controller 的辅助方法?有没有办法在不破解/修补 Rails 的情况下禁用它? 最佳答案 @George Schreib
我正在使用带有最新 ADT 插件的 Eclipse Kepler SP2。每隔一分钟 Eclipse 就会说“为 Android 4.4.2 加载数据”并阻止我想做的一切。我在不同的文件夹中有几个 E
我是一名优秀的程序员,十分优秀!