如何创建一个“增量”函数,它接受整数指针并增加其值?

问题描述 投票:2回答:2

this教程中,给出了以下代码:

fn increment(r: &mut int) {
    *r = *r + 1;
}

fn main () {
    let mut x = ~10;
    increment(x);
}

我知道这个语法已经过时了,所以我自己移植了代码:

fn increment(r: &mut i32) {
    *r = *r + 1;
}

fn main() {
    let mut x = Box::new(10);
    increment(x);
}

当我尝试编译时,我收到以下错误:

error[E0308]: mismatched types
 --> src/main.rs:8:15
  |
8 |     increment(x);
  |               ^ expected &mut i32, found struct `std::boxed::Box`
  |
  = note: expected type `&mut i32`
             found type `std::boxed::Box<{integer}>`

我尝试了很多与&符号,muts等的组合。制作这种功能的正确方法是什么?

pointers rust
2个回答
6
投票

首先,您的教程已经过时了。有一个伟大的official book

其次,除非你真的需要,否则你不应该使用盒子。也就是说,不写这个:

let mut x = Box::new(10);

写这个:

let mut x = 10;

除非你真的知道为什么你需要Box<i32>。简而言之,需要三个方面的框:递归类型,特征对象和传递非常大的结构。

第三,是的,作为A.B.说,你需要使用&mut参考:

let mut x = 10;
increment(&mut x);

这里没有必要取消引用因为x不再是Box,它只是一个常规值。


1
投票

我试图让add_one()函数在Box<i32>上工作,最后让它像在这个例子中一样工作:

fn main() {
    let mut x = Box::new(5);

    println!("{:?}", x);
    println!("{:?}", *x);

    //  Taking a mutable reference to the dereference of x.
    add_one(&mut *x);

    println!("{:?}", x);

    boxed_add_one(&mut x);

    println!("{:?}", x);

}

// Gets a reference to a mutable int
fn add_one(num: &mut i32) {
    *num += 1;
}

// Gets a reference to a mutable box with int
fn boxed_add_one(b: &mut Box<i32>) {
    let ref mut num = **b;
    *num += 1;
}
© www.soinside.com 2019 - 2024. All rights reserved.