rust - 如何根据泛型类型是否实现特征以不同方式实现函数?
问题描述
我想do_something
根据泛型类型是否实现来实现有条件T
的Debug
。有没有办法做这样的事情?
struct A(i32);
#[derive(Debug)]
struct B(i32);
struct Foo<T> {
data: T,
/* more fields */
}
impl<T> Foo<T> {
fn do_something(&self) {
/* ... */
println!("Success!");
}
fn do_something(&self)
where
T: Debug,
{
/* ... */
println!("Success on {:?}", self.data);
}
}
fn main() {
let foo = Foo {
data: A(3), /* ... */
};
foo.do_something(); // should call first implementation, because A
// doesn't implement Debug
let foo = Foo {
data: B(2), /* ... */
};
foo.do_something(); // should call second implementation, because B
// does implement Debug
}
我认为做到这一点的一种方法是创建一个我们必须定义的特征do_something(&Self)
,但我不确定。我的代码片段是我将首先尝试的。
解决方案
这是基于夜间功能专业化的解决方案:
#![feature(specialization)]
use std::fmt::Debug;
struct A(i32);
#[derive(Debug)]
struct B(i32);
struct Foo<T> {
data: T,
/* more fields */
}
trait Do {
fn do_something(&self);
}
impl<T> Do for Foo<T> {
default fn do_something(&self) {
/* ... */
println!("Success!");
}
}
impl<T> Do for Foo<T>
where
T: Debug,
{
fn do_something(&self) {
/* ... */
println!("Success on {:?}", self.data);
}
}
fn main() {
let foo = Foo {
data: A(3), /* ... */
};
foo.do_something(); // should call first implementation, because A
// doesn't implement Debug
let foo = Foo {
data: B(2), /* ... */
};
foo.do_something(); // should call second implementation, because B
// does implement Debug
}
第一步是创建一个定义do_something(&self)
. 现在,我们为 定义impl
了这个 trait 的两个:一个为所有人实现Foo<T>
的通用“父级”和一个仅针对 implements 的子集实现的专用“子级” 。孩子可能会专门研究来自父母的物品。这些我们要专门化的项目需要在 parent 中用关键字进行标记。在您的示例中,我们希望专门化.impl
T
impl
T
Debug
impl
impl
default
impl
do_something
推荐阅读
- c# - MongoDB.net 驱动程序 - 项目到不同的类
- selenium-chromedriver - Chrome 下拉菜单的语言不会改变。Python 硒 chromedriver
- python - 在 OpenCV C++ 中转换 Keras VGG16 预处理
- c# - 带有名称的 Swagger 枚举
- angular - 用于输入、可访问性的 Angular、可重用组件和标签
- javascript - 移动端的 JQuery $(document).on("click")
- angular - 分别实现显示更多和更少按钮
- c# - 如何在没有 Roslyn 的情况下将 Property1.Property2 之类的路径评估为已编译的表达式
- android - 从 WebView Android 中加载的网站下载文件的路径
- javascript - 是否可以在客户端的前端使用 React 服务器环境变量?