返回Rust中的类型

  • 本文关键字:类型 Rust 返回 rust
  • 更新时间 :
  • 英文 :


我正在尝试创建一个特征(StringToTable(,该特征返回一个具有另一个特征的实现的结构(Table(。

当我读到这个答案时,如何推断函数的返回类型?,我尝试了"盒装式"的方法,但没有成功。

我不知道调用StringToTable时的结构类型,所以我不能使用类似于'to_table<T>'或'StringToTable<T>'。。

出现错误的游乐场:https://play.rust-lang.org/?version=stable&mode=调试&edition=2018&gist=cac035a6e6357c204156 fab13449e865

我的代码:

1°进近:

fn to_table(table: String) -> Option<Box<dyn Table<DeserializeOwned + Serialize + SearchIndex>>>;

我得到了:

error[E0225]: only auto traits can be used as additional traits in a trait object
--> src/main.rs:18:75
|
18 |     fn to_table(table: String) -> Option<Box<dyn Table<DeserializeOwned + Serialize + SearchIndex>>>;
|                                                        ----------------   ^^^^^^^^^
|                                                        |                  |
|                                                        |                  additional non-auto trait
|                                                        |                  trait alias used in trait object type (additional use)
|                                                        first non-auto trait
|                                                        trait alias used in trait object type (first use)

2°进近:

fn to_table2(table: String) -> Option<Box<dyn Table<T>>> where T: DeserializeOwned + Serialize + SearchIndex;

我得到了:

error[E0412]: cannot find type `T` in this scope
--> src/main.rs:20:68
|
20 |     fn to_table2(table: String) -> Option<Box<dyn Table<T>>> where T: DeserializeOwned + Serialize + SearchIndex;
|                                                                    ^ not found in this scope

**我的代码已被简化

我想做的是:在tcp服务器上接收一个随机名称,并为其获取等效的结构

在第二种方法中,您可以通过声明类型参数T来修复编译错误。您可以对函数或特性执行此操作。

关于功能:

fn to_table2<T>(table: String) -> Option<Box<dyn Table<T>>> where T: DeserializeOwned + Serialize + SearchIndex;

关于特征:

pub trait StringToTable<T> where T: DeserializeOwned + Serialize + SearchIndex {
fn to_table2(table: String) -> Option<Box<dyn Table<T>>>;
}

另一种选择是使用关联类型:

pub trait StringToTable {
type T : DeserializeOwned + Serialize + SearchIndex;
fn to_table2(table: String) -> Option<Box<dyn Table<Self::T>>>;
}

最新更新