2015-11-26 16 views
3

我有以下幾點:如何將具有2個參數的函數作爲參數傳遞給函數?

fn apply_bin(&mut self, op: Fn(i32,i32)) -> Result<i32, String> { 

} 

,但我得到的錯誤:

<anon>:75:29: 75:31 error: the trait `core::marker::Sized` is not implemented for the type `core::ops::Fn(i32, i32) + 'static` [E0277] 
<anon>:75  fn apply_bin(&mut self, op: Fn(i32,i32)) -> Result<i32, String> { 
             ^~ 

這是爲什麼?如何解決?

回答

6

您可以使用一個通用的方法,因爲Fn是一個特點:

fn apply_bin<F>(&mut self, op: F) -> Result<i32, String> 
    where F: Fn(i32, i32) 
{ 
} 

(這是靜態調度)

您也可以使用動態調度:

fn apply_bin(&mut self, op: &Fn(i32, i32)) -> Result<i32, String> 
{ 
} 

有更多信息在book

+0

謝謝!這似乎工作:D –

相關問題