我正在尝试定义一个函数,它将引用作为参数,并在引用的对象上调用泛型方法,传递一个具体的值.我需要一种方法来要求传递给我的函数的泛型类型是函数将使用它的具体类型的特征.我似乎无法弄清楚如何做到这一点.
我试图实现的那种事情的最小例子:
trait Vehicle {}
trait Floating {}
struct Boat;
impl Vehicle for Boat {}
impl Floating for Boat {}
fn main() {
let mut a: Vec<Box<Vehicle>> = vec![];
populate(&mut a); // Does not compile
let mut b: Vec<Box<Floating>> = vec![];
populate(&mut b); // Also does not compile
}
fn populate(receiver: &mut Vec<Box<Boat>>) { // What should I put here?
receiver.push(Box::new(Boat{}));
}
Run Code Online (Sandbox Code Playgroud)
尝试编译它会产生以下错误:
error[E0308]: mismatched types
--> src/main.rs:10:14
|
10 | populate(&mut a); // Does not compile
| …Run Code Online (Sandbox Code Playgroud) 我有一个if-then-else语句,我想将其转换为三元运算符,但是我不知道为什么我不能这样做。代码如下:
public Movie create(NewMovieDTO newMovieDTO) {
Movie movieForSaving = NewMovieDTOToMovie.map(newMovieDTO);
List<Actor> actorsForSaving = new ArrayList<Actor>();
movieForSaving.getActors().forEach((actor) -> {
Optional<Actor> actorInDatabase = actorService
.findByNameAndSurname(actor.getName(), actor.getSurname());
if(actorInDatabase.isPresent()) {
actorForSaving.add(actorInDatabase.get());
} else {
actorForSaving.add(actor);
}
});
movieForSaving.setActors(actorForSaving);
return movieRepository.save(movieForSaving);
}
Run Code Online (Sandbox Code Playgroud)
三元运算符的代码是:
public Movie create(NewMovieDTO newMovieDTO) {
Movie movieForSaving = NewMovieDTOToMovie.map(newMovieDTO);
List<Actor> actorsForSaving = new ArrayList<Actor>();
/*Line 1*/ movieForSaving.getActors().forEach((actor) -> {
Optional<Actor> actorInDatabase = actorService
.findByNameAndSurname(actor.getName(), actor.getSurname());
/*Line 2*/(actorInDatabase.isPresent()) ? actorForSaving.add(actorInDatabase.get()) : actorForSaving.add(actor);
/*Line 3*/});
movieForSaving.setActors(actorForSaving);
return movieRepository.save(movieForSaving);
}
Run Code Online (Sandbox Code Playgroud)
IDE给出以下错误:
第1行:此表达式的目标类型必须是功能接口
第2行:此行有多个标记
- Syntax …Run Code Online (Sandbox Code Playgroud)