私はC++ std::bind
と似たようなことをして、別の関数の引数としてバインドされた関数ポインタを渡したいと思います。構造体インスタンスの関数ポインタを関数の引数(C++のstd :: bindのようなもの)
以下のコードは失敗した試行を示し、私が何をしようとしているかを示しています。
pub struct MyStruct {
x: i64
}
impl MyStruct {
pub fn struct_function(&mut self, val: i64) {
self.x += val;
}
}
fn normal_function(val: i64) {
println!("sum -> {}", val + 1);
}
fn do_something_with_a_function(f: fn(i64)) {
f(23);
}
fn main() {
// This works as you'd expect
do_something_with_a_function(normal_function as fn(i64));
// What I'd like to do
// This attempts to use a closure, but throws an error.
let instance = MyStruct{x: 0};
let instance_function = |val: i64|{instance.struct_function(val)};
do_something_with_a_function(instance_function as fn(i64));
}
エラー:
error: non-scalar cast:
[[email protected]/main.rs:25:29: 25:72 instance:&mut MyStruct]
asfn(i64)