我有各种结构,都实现相同的特征.我想在某些条件下进行分支,在运行时决定实例化哪些结构.然后,无论我遵循哪个分支,我都想从该特征中调用方法.
这可能在Rust吗?我希望实现类似下面的内容(不编译):
trait Barks {
fn bark(&self);
}
struct Dog;
impl Barks for Dog {
fn bark(&self) {
println!("Yip.");
}
}
struct Wolf;
impl Barks for Wolf {
fn bark(&self) {
println!("WOOF!");
}
}
fn main() {
let animal: Barks;
if 1 == 2 {
animal = Dog;
} else {
animal = Wolf;
}
animal.bark();
}
Run Code Online (Sandbox Code Playgroud) 在玩Diesel时,我遇到了写一个函数的问题,该函数将Strings 的向量作为输入并执行以下操作:
Strings 组合到一个大型查询中ConnectionVec如果我一步构建查询,它可以正常工作:
fn get_books(authors: Vec<String>, connection: SqliteConnection) {
use schema::ebook::dsl::*;
let inner = author
.like(format!("%{}%", authors[0]))
.and(author.like(format!("%{}%", authors[1])))
.and(author.like(format!("%{}%", authors[2])));
ebook
.filter(inner)
.load::<Ebook>(&connection)
.expect("Error loading ebook");
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试以更多步骤生成查询(为了使用输入向量的可变长度需要),我无法编译它:
fn get_books(authors: Vec<String>, connection: SqliteConnection) {
use schema::ebook::dsl::*;
let mut inner = author
.like(format!("%{}%", authors[0]))
.and(author.like(format!("%{}%", authors[1]))); // <1>
inner = inner.and(author.like(format!("%{}%", authors[2]))); // <2>
ebook
.filter(inner)
.load::<Ebook>(&connection)
.expect("Error loading ebook");
}
Run Code Online (Sandbox Code Playgroud)
这会生成以下错误:
inner = inner.and(author.like(format!("%{}%",authors[2])));
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `diesel::expression::operators::Like`, …Run Code Online (Sandbox Code Playgroud)