![](/img/trans.png)
[英]How can I pass a FnMut closure to a function using a reference in Rust?
[英]How can I obtain the address of a closure in Rust?
let say_hello = || println!("hello");
如何顯示閉包地址?
您可以使用原始指針轉換:
fn main() {
let say_hello = || println!("hello");
let address = (&say_hello as *const _) as usize;
println!("{address}");
}
還使用std::ptr::addr_of
並再次投射:
let same_address = std::ptr::addr_of!(say_hello) as usize;
這個問題的答案實際上取決於您是指閉包 object 本身,還是閉包的調用 function。
例如,在這種情況下,閉包捕獲一個變量:
let mut foo = 0;
let mut bar = || foo += 1;
因此, bar
必須在其中攜帶一個&mut foo
。
因此,實際運行的代碼地址與閉包地址 object 不同。
要具體說明這種區別,請檢查以下示例:
fn foo() {}
let bar = foo; // `bar` itself is the address of the code for foo.
println!("{:?}", bar as usize); // Prints the address of the code of foo.
println!("{:?}", &bar as *const _ as usize); // Prints the address of `bar`
第二行基本上就是@Netwave 上面的回答。
如果您正在尋找第一種情況,那么這不一定總是可能的。
如果您的閉包捕獲項目,則無法將其轉換為穩定 rust 中代碼的地址,因為這需要您有權訪問它的FnOnce
/ Fn
/ FnMut
。 但是,如果您對不穩定的 rust 沒問題,那么您可以這樣做:
#![feature(unboxed_closures, fn_traits)]
fn main() {
let mut x = 0;
let mut foo = || x += 1;
print_addr(foo);
}
fn print_addr<F: FnMut()>(_: F) {
println!("{:?}", <F as std::ops::FnMut<()>>::call_mut as usize);
}
如果您的閉包沒有捕獲任何內容,那么獲取地址的正確方法是將其轉換為 function 指針,然后將其轉換為數字:
fn main() {
let foo = || println!("Abc");
println!("{:?}", foo as fn() as usize);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.