我有一个结构,有时我静态实例化,有时我想让用户在堆上分配.是否可以同时允许函数作为参数?
pub struct MyData {
x: i32
}
static ALLOCATED_STATICALLY: MyData = MyData {x: 1};
// what should my signature be?
fn use_data(instance: Box<MyData>) {
println!("{}", instance.x);
}
fn main () {
use_data(Box::new(MyData{x: 2}));
// this doesn't work currently
use_data(ALLOCATED_STATICALLY);
}
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,您都可以传递指向该函数的指针.
pub struct MyData {
x: i32
}
static ALLOCATED_STATICALLY: MyData = MyData { x: 1 };
// what should my signature be?
fn use_data(instance: &MyData) {
println!("{}", instance.x);
}
fn main () {
use_data(&Box::new(MyData{ x: 2 }));
use_data(&ALLOCATED_STATICALLY);
}
Run Code Online (Sandbox Code Playgroud)
请注意,在这两种情况下,调用者都需要使用&运算符来获取值的地址.在第一次调用中,运算符产生a &Box<MyData>,但编译器会自动将其转换为a&MyData因为Box实现了Dereftrait.
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |