2015-10-10 53 views
5

我有一个结构,有时我静态实例化,有时我想用户在堆上分配。是否可以允许两个参数作为一个函数?允许静态变量和框作为函数参数吗?

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

回答

9

在这两种情况下,都可以将指针传递给函数。

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

注意,在这两种情况下,调用者需要使用&操作者采取的值的地址。在第一次调用中,运算符产生&Box<MyData>,但编译器自动将其转换为&MyData,因为Box实现了Deref trait

+2

说“参考”而不是“指针”可能会更好。后者让我想到一个*原始指针*'* const T'。 – Shepmaster

相关问题