小编fer*_*rux的帖子

通过引用将值传递给函数并通过Box传递它有什么区别?

将值传递给函数并通过"Box"传递给函数有什么区别:

fn main() {
    let mut stack_a = 3;
    let mut heap_a = Box::new(3);

    foo(&mut stack_a);
    println!("{}", stack_a);

    let r = foo2(&mut stack_a);
    // compile error if the next line is uncommented
    // println!("{}", stack_a);

    bar(heap_a);
    // compile error if the next line is uncommented
    // println!("{}", heap_a);
}

fn foo(x: &mut i32) {
    *x = 5;
}

fn foo2(x: &mut i32) -> &mut i32 {
    *x = 5;
    x
}

fn bar(mut x: Box<i32>) {
    *x = 5;
} …
Run Code Online (Sandbox Code Playgroud)

rust

44
推荐指数
3
解决办法
2万
查看次数

标签 统计

rust ×1