2015-07-15 12 views
5

In rust-clippy, abbiamo la funzione following:Come scrivere una funzione generica su un tipo di puntatore?

fn over<X, F>(left: &[X], right: &[X], mut eq_fn: F) -> bool 
     where F: FnMut(&X, &X) -> bool { 
    left.len() == right.len() && left.iter().zip(right).all(|(x, y)| 
     eq_fn(x, y)) 
} 

Si dà il caso, la rappresentazione AST rustc s' utilizza un sacco di syntax::ptr::P<T> puntatori. Quei dereferenziamento a T, e così autodeposto, li costringe implicitamente a &T se usiamo una chiusura. Se cerchiamo di usare una pianura fn tuttavia, otteniamo un tipo non corrispondente:

error: type mismatch: the type `fn(&syntax::ast::Expr, &syntax::ast::Expr) -> bool {eq_op::is_exp_equal}` implements the trait `for<'r, 'r> core::ops::FnMut<(&'r syntax::ast::Expr, &'r syntax::ast::Expr)>`, but the trait `for<'r, 'r> core::ops::FnMut<(&'r syntax::ptr::P<syntax::ast::Expr>, &'r syntax::ptr::P<syntax::ast::Expr>)>` is required (expected struct `syntax::ptr::P`, found struct `syntax::ast::Expr`) [E0281]

Posso cambiare la funzione di cui sopra ad accettare sia &[&T] e &[P<T>] e automaticamente costringere P<Expr> in &Expr? Se é cosi, come?

risposta

9

Sia &T e P<T> implementare Deref<Target = T>, così si potrebbe usare che nei vostri limiti:

use std::ops::Deref; 

fn over<X, F, X1, X2>(left: &[X1], right: &[X2], mut eq_fn: F) -> bool 
     where X1: Deref<Target = X>, 
       X2: Deref<Target = X>, 
       F: FnMut(&X, &X) -> bool { 
    left.len() == right.len() && left.iter().zip(right).all(|(x, y)| 
     eq_fn(x, y)) 
} 
Problemi correlati