2015-07-15 21 views
5

W rust-clippy mamy following funkcję:Jak napisać ogólną funkcję nad typem wskaźnika?

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)) 
} 

Jak to się dzieje, rustc „s reprezentacja AST zużywa dużo syntax::ptr::P<T> wskaźników. Te dereferencje do T, a więc autoderef domyślnie wymusza ich na &T, jeśli użyjemy zamknięcia. Jeśli staramy się używać zwykłego fn jednak otrzymujemy niedopasowanie typu:

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]

mogę zmienić powyższą funkcję do zaakceptowania zarówno &[&T] i &[P<T>] i automatycznie zmusić P<Expr> do &Expr? Jeśli tak to jak?

Odpowiedz

9

Zarówno &T i P<T> wdrożyć Deref<Target = T>, więc można używać, że w swoich granicach:

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)) 
} 
Powiązane problemy