标签: mutable

函数参数如何允许改变变量但不能指向任何其他变量?

我想要一个调用其他相互递归函数的函数,但我已经有了这样的类型签名:

fn f1(mut index: &mut usize, ..)
fn f2(mut index: &mut usize, ..)
Run Code Online (Sandbox Code Playgroud)

我真的想要一组相互递归的函数,它们只能改变 index我在main()函数中定义的变量,并且不能指向任何其他变量。

我已经阅读了变量名之前的“mut”和“:”之后的“mut”有什么区别?中的两个答案。,我已经尝试了几种方法,但仍然无法实现我想要的。我想我不太理解这些概念。

这是我目前理解的证据:

// with &mut I can change the referred value of n, but then I can't
// pass a mutable reference anywhere
fn mutate_usize_again(n: &mut usize) {
    *n += 1;
    // n += 70; ^ cannot use `+=` on type `&mut usize`
}

fn mutate_usize_two_times(mut n: &mut usize) {
    *n = 8;
    // if I don't write mut …
Run Code Online (Sandbox Code Playgroud)

reference mutable immutability rust

0
推荐指数
1
解决办法
1176
查看次数

通过 const 限定对象调用成员函数会出现错误,因为函数未标记为 const?

代码

#include <iostream>
class A
{
public:
    mutable int x;
    mutable int y;

    A(int k1 = 0, int k2 = 0) :x(k1), y(k2) {}

    void display()
    {
        std::cout << x << "," << y << "\n";
    }
};

int main()
{
    const A a1;
    a1.x = 3;
    a1.y = 8;
    a1.display();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出

Error: 'this' argument to member function 'display' 
        has type 'const A', but function is not marked const
Run Code Online (Sandbox Code Playgroud)

我只是A::display()通过const限定对象调用成员函数a1。那么为什么 line …

c++ class constants mutable member-functions

0
推荐指数
1
解决办法
604
查看次数

我什么时候应该关闭mut?

假设我有这个代码:

let mut s = "hi".to_string();
let c = || s.push_str(" yo");
c();
Run Code Online (Sandbox Code Playgroud)

它不会编译并生成此错误:

error[E0596]: cannot borrow `c` as mutable, as it is not declared as mutable                 
   --> src\test.rs:120:9
    |
119 |         let c = || s.push_str(" yo");
    |             -      - calling `c` requires mutable binding due to mutable borrow of `s`  
    |             |
    |             help: consider changing this to be mutable: `mut c`
120 |         c();
    |         ^ cannot borrow as mutable

For more information about this error, try …
Run Code Online (Sandbox Code Playgroud)

closures mutable mutability rust

0
推荐指数
1
解决办法
214
查看次数

为什么 C++11 中 const 成员函数可以修改对象的可变数据成员?

成员函数为什么以及如何const修改对象的mutable数据成员?

成员函数使用this指针来修改对象的数据成员。this成员函数的指针是const指向常量的指针,而不是普通的数据成员。那么为什么总是可以修改mutable对象标记的数据成员,编译器是如何实现的呢?

c++ mutable c++11

0
推荐指数
1
解决办法
110
查看次数

在python中复制可变列表

如何不更改列表的值???

>>> a=range(0,5)
>>> b=10
>>> c=a
>>> c.append(b)
>>> c
[0, 1, 2, 3, 4, 10]
>>> a
[0, 1, 2, 3, 4, 10]
Run Code Online (Sandbox Code Playgroud)

直到今天我还不知道python中的列表是可变的!

python mutable

-1
推荐指数
1
解决办法
622
查看次数

-2
推荐指数
1
解决办法
169
查看次数