我如何通过一个数组给函数在锈并更改其内容? [英] How do I pass an array to a function in Rust and change its content?

查看:122
本文介绍了我如何通过一个数组给函数在锈并更改其内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递一个数组给一个函数,然后将里面的内容。我怎样才能做到这一点,这是我的code以下,但当然这是行不通的。

I want to pass an array to a function and change the content inside it. How can I do that, this is my code below, but of course it doesn't work.

fn change_value(mut arr: &[int]) {
    arr[1] = 10;
}

fn main() {
    let mut arr: [int, ..4] = [1, 2, 3, 4];
    change_value(arr);
    println!("this is {}", arr[1]);
}

我得到的错误:不能分配给一成不变的VEC含量改编[..]

我一直在寻找周围,但作为pretty新手锈程序员,我无法找到任何东西。同时它没有帮助,防锈改变其语言颇多所以很多这样的方法去precated或删除。

I've been searching around, but as a pretty novice Rust programmer, I can't find anything. Also it doesn't help that Rust changes its language quite a lot so a lot of methods of doing this are deprecated or removed.

推荐答案

锈病引用(记为&安培; 符号)有两种:不可变的(& T公司)和可变(&放大器; MUT牛逼)。为了改变参考后面的值,这个参考必须是可变的,所以你只需要通过&放大器; MUT [INT] 来的函数,而不是&放大器; [INT]

Rust references (denoted by & sign) are of two kinds: immutable (&T) and mutable (&mut T). In order to change the value behind the reference, this reference has to be mutable, so you just need to pass &mut [int] to the function, not &[int]:

fn change_value(arr: &mut [int]) {
    arr[1] = 10;
}

fn main() {
    let mut arr: [int, ..4] = [1, 2, 3, 4];
    change_value(&mut arr);
    println!("this is {}", arr[1]);
}

您也不必在 change_value 参数 MUT改编,因为 MUT 有表示不是指向数据的变量的可变性。所以,用 MUT ARR:放大器; [INT] 您可以重新分配改编本身(它指向一个不同片),但你不能改变它的引用。

You also don't need mut arr in change_value argument because mut there denotes mutability of that variable, not of the data it points to. So, with mut arr: &[int] you can reassign arr itself (for it to point to a different slice), but you can't change the data it references.

这篇关于我如何通过一个数组给函数在锈并更改其内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆