312 questions
5
votes
1
answer
91
views
With &mut self, why can't this method move and replace a field's value?
I'm trying to implement a binary search tree. The parent struct, BinSearchTree, has a pointer to a root node:
pub struct BinSearchTree {
root: Option<Box<Node>>,
size: u32,
}
...
0
votes
0
answers
28
views
Avoid cloning rust hashmap [duplicate]
When iterating over a hashmap, I want to conditionally remove some entries. Matching with mut map gives me mutable access to the hashmap stored in Wrapper. Attempting to loop over the entries with for ...
0
votes
1
answer
51
views
Simultaneous Mutable and Immutable HashMap gets
I'm working with a struct Node and node_map defined as
pub struct Node<'a> {
id: i32,
next: HashMap<String, &'a Node<'a>>,
}
let mut node_map = HashMap::<i32, ...
0
votes
0
answers
92
views
Mutability of numpy arrays and Python lists as function arguments
I'd like advice on how numpy arrays and Python lists are passed into functions. Specifically, VBA and other languages I'm familiar with can be explicit in the function definition if an argument is ...
0
votes
0
answers
79
views
Why can't record struct contain init property?
This is my C# code:
record struct recName(int A) { }
And this is generated code behind the scenes:
internal struct recName : IEquatable<recName>
{
public recName(int A)
{
<A&...
0
votes
0
answers
55
views
Cannot borrow `p` as mutable more than once at a time [duplicate]
I'm trying to figure out exactly why I get this compile error in this very simple code;
cannot borrow p as mutable more than once at a time
as I do not store p more than once mutably; either ...
0
votes
2
answers
98
views
How to debug without changing all the function signatures?
I'm learning Rust by reading the book and doing rustlings and watching videos; I think I understand what's happening here, but I don't understand what to do about it.
#[derive(Debug)]
enum Message {
...
1
vote
2
answers
81
views
Trying to understand Mutability. Modify Reference vs. modify Object
I am trying to understand mutability.
When I declare a variable in Rust with
let mut a = String::from("Foo");
I can modify the Object, e.g.:
a.push_str("Bar");
Or assign a new ...
1
vote
1
answer
76
views
Temporarily Mutating Immutable Structs
I am attempting to create something similar to the code below. Is it safe to cast raw pointers as such given that I am only temporarily modifying the immutable struct (I undo the changes I make)?
#[...
3
votes
1
answer
144
views
Why can't I borrow as mutable more than once at a time in this example? [duplicate]
Minimal example of a game with a player which owns a position and walks as time passes. The following compiles:
use std::thread::sleep;
use std::time::Duration;
struct Player {
position: usize,
}
...
0
votes
1
answer
113
views
Dealing with unknown mutability in rust
I'm having trouble understanding when to use mutable references as opposed to immutable references in traits.
The following example for a Visitor implementation is taken from Rust Design Patterns:
mod ...
2
votes
1
answer
123
views
Shallow Copying Class Objects vs. String Variables
string a = "John";
string b = "Doe";
a = b; // Shallow copying strings
b = "Elon Musk";
Console.WriteLine(a); // Output: Doe
This prints "Doe", meaning the ...
1
vote
1
answer
97
views
I can write an immutable variable in rust
let mut a = Box::new("123".to_string());
let b = Box::new( &mut a);
b.push('4');
assert_eq!( "1234", b.as_str());
// lets see the types:
// let x001: Box<&...
0
votes
1
answer
165
views
"mut" location is unintuitive but works. Why?
In order to learn Rust I'm just writing trivial programs. Here I've written a LinkedList with an insert function that adds nodes to the end of the list. The function works as expected but I don't ...
1
vote
1
answer
290
views
How do you mutate data in Rust Wasm? Getting borrow checker errors
I've tried everything from Rc to Arc and Mutex async_std which wouldn't even compile despite it apparently including wasm support.
I've been fighting with this error for a few days now and I can't ...
1
vote
1
answer
152
views
Why an implement of immutable trait can be mutable?
Here is my code, it can compile
trait AppendBar {
fn append_bar(self) -> Self;
}
impl AppendBar for Vec<String> {
fn append_bar(mut self) -> Self {
self.push("Bar&...
1
vote
1
answer
75
views
Mutability of a class after conforming to protocol is in question
I was trying to implement a Networking Module for my personal project and I was following TDD. When I am writing the test cases I came across a compile error and I was not able to map the error with ...
0
votes
1
answer
64
views
How can I separate these structs to avoid undefined behavior from multiple mutable references?
I'm working on extending an interpreter written in Rust to support executing code in a new format. I have two structs—LanguageAContext and LanguageBContext— where the latter needs mutable access to ...
0
votes
1
answer
84
views
How to call FnMut stored in the collection? (error: cannot borrow `*handler` as mutable, as it is behind a `&` reference)
I'm a newbuy in Rust. I need to store a collection of closures (fn_list) that can use variables from the context, after that I need to call these closures.
Playground code:
pub struct MyScope {
...
2
votes
2
answers
2k
views
Why &mut self in method when modifying an object as field in a struct
I still struggle to grasp why &mut self is required to modify the internal state of an object owned by my struct. I understand why I have to use at least &self, because I don't want to consume ...
0
votes
0
answers
46
views
Use references/pointers to JS Array declared outside of function
I am writing a small tictactoe game in Angular.
I have a function checkForWin() which checks all the possible winning combinations for a win. (Horizontal, Vertical, and Diagonal)
The function works ...
0
votes
0
answers
133
views
Val and Overrides in Scala
As i understand vals are immutable in Scala. However in case of inheritance we can override a val defined in the base class. If the val member already got created when the base class was constructed ...
1
vote
2
answers
315
views
Why shouldn't builder pattern implementations be immutable?
Consider the following Kotlin implementation of a string builder:
class StringBuilder {
private val items = mutableListOf<String>()
fun append(item: String): StringBuilder {
...
0
votes
2
answers
251
views
In Rust, how do you pass a function with a mutable parameter to be used in parllel?
I've been playing around with collision detection, and I've been working on a function that collides two sets of objects with each other. To allow it to be run in parallel, only the first set is ...
1
vote
1
answer
82
views
how do i share a mutable variable between threads?
i need to have a thread that recursively checks a variable while the main thread changes the variable. however, it appears that with move, the variable is not being changes by the lambda in register. (...
2
votes
2
answers
2k
views
Efficient way to update a single element of a Polars DataFrame?
Polar's DataFrame does not provide a method to update the value of a single cell. Instead, we have to use the DataFrame.apply or DataFrame.apply_at_idx methods that update a whole column / Series. ...
0
votes
1
answer
86
views
How to dissociate mutability from lifetime in Rust?
I want to have two types (in my question-fitted examples I will mark them as IdHandler counting IDs, and IdUser using the IDs), where the dependent one of them should not outlive (hence, lifetimes) ...
0
votes
1
answer
73
views
Get reference to a specific struct in a Vector to modify it
I'm starting my first project in Rust. I try to make a Zwave crate.
I'm stuck with the problem of ref sharing. For now, the code is divided in 3 structs:
Network, which contains global Zwave network ...
0
votes
0
answers
79
views
Javascript: Why don't array methods return a new array?
I understand that the reason methods on strings return a new string is that strings are immutable, so the method can't modify the string you pass to it.
With an array, if you pass it to a method, that ...
0
votes
1
answer
173
views
Can't borrow mutable values inside loop
I'm trying to remove an element from an array:
pub fn update(arr: &mut Vec<Pipe>) {
// move pipes
for pipe in arr.iter_mut() { //first mutable borrow occurs here
...
2
votes
1
answer
667
views
How to get mutable reference to object inside vec inside a struct in rust?
I have a very basic problem in a rust relating to mutability of objects inside a vector. I have a need to get a mutable reference to an object from within a method of the struct as follows:
struct ...
0
votes
1
answer
119
views
Borrowing parts of structs without RefCell
According to this question, it is not possible to borrow parts of a struct, only the entire struct. This makes sense, however I would not expect the following code (playground) to compile, which it ...
0
votes
2
answers
91
views
Sudoku Solver - Modify a list in-place within a recursive function
This is leetcode #37 (Sudoku solver).
I have a question regarding modifying an input list in-place within a recursive function. The code below pretty much does the job as the print(board) does print ...
-2
votes
1
answer
58
views
Why do Python iterable and non-iterable keyword argument types behave differently with multiple function calls? [duplicate]
I was reading this very informative question and answer and learned about this behavior for the first time: calling
def foo(l=[]):
l.append(1)
print(l)
foo()
foo()
foo([])
foo()
prints
[1]
[...
0
votes
1
answer
287
views
Changing a mutable value in a class inheriting from a sealed class with an immutable value
In Kotlin, I'm trying to have a mutable generic value in sealed class A, and a mutable generic Number value in sealed class B with a mutable Long/... value in final C/...; but whenever I change A and ...
4
votes
1
answer
720
views
Rust - double mutable borrow in 'while let' statement [duplicate]
Sorry if this is a dumb question, I'm relatively new with Rust and just can't crack this double mutable borrowing error. I'm trying to create an AVL tree method that finds an appropriate position into ...
0
votes
2
answers
115
views
I'm unable to understand how to borrow an item from a vector mutably in Rust
I can't make this code work, I understand I need to change the self reference to a mutable reference but this will just spawn a new set of errors.
struct Context {
values: Vec<u32>,
}
trait ...
0
votes
3
answers
373
views
When should I make a closure mut?
Let's say I have this code:
let mut s = "hi".to_string();
let c = || s.push_str(" yo");
c();
It doesn't compile and generates this error:
error[E0596]: cannot borrow `c` as ...
3
votes
1
answer
746
views
Why are the values in a given HashMap mutable when I don't believe I have explicitly declared them as such?
I wrote a working solution to the third proposed exercise in section 8.3 of The Book, but some of the behavior defies my intuition. Specifically, it appears that I'm able to mutate a vector that ...
2
votes
1
answer
35
views
Copying objects in js (need guidance on pass by reference from docs)
I looked in the js docs and while studying the doc it mentioned in object.assign()
If the source value is a reference to an object, it only copies the reference value.
In my below snippet, one alters ...
0
votes
1
answer
37
views
Prae:Wrapper: need to use iter_mut of interior Vec but Prae:Wrapper only provides immutable access
I'm using the prae crate for validation and the following function gives me errors:
fn advance_rotors(&mut self) {
self.rotors.get()[0].rotate();
let mut iterhandle = self.rotors.iter_mut()....
0
votes
4
answers
246
views
Iterating and modifying a list of numpy arrays leave arrays unchanged [duplicate]
Consider the two following codes:
import numpy as np
mainlist = [np.array([0,0,0, 1]), np.array([0,0,0,1])]
for i in range(len(mainlist)):
mainlist[i] = mainlist[i][0:2]
print(mainlist) # [...
0
votes
2
answers
283
views
use an object inside a closure which is passed to a method of that object
i have a struct Screen with its implementation
pub struct Screen {
stdin: Stdin,
// types are irrelevant
stdout: MouseStdout,
}
impl Screen {
// ...
pub fn handle_keys_loop<F: ...
0
votes
0
answers
14
views
a python question about list, append and mutability [duplicate]
Here is my code:
list1 = ["dog", "cat"]
list2 = list1
list2.append ("fish")
print(list1)
print(list2) # both list1 and list2 will be [“dog”, “cat”, “fish”].
I do ...
0
votes
1
answer
545
views
While loop with next() vs foreach
I was going through some third party code and I ran onto this snippet for going through an array. Since this is a respectful code base I'm wandering what is the secret behind the trouble of moving ...
1
vote
1
answer
73
views
Add a new property to an object from an array of objects in Javascript
I am trying to add a new property to an object which is part of an array of objects.
The main array looks like this:
0: {key: 'Fruits', props: Array(22)}
1: {key: 'Dried', props: Array(1)}
2: {key: '...
3
votes
1
answer
267
views
In Haskell, does mutability always have to be reflected in type system?
I'm new to Haskell, so please forgive if this question is dumb.
Imagine that we have two data structures bound to the names x and y.
x is mutable.
y is not.
As a matter or principle, does x ...
0
votes
1
answer
1k
views
Python: bytearray object becomes bytes (immutable) when populated
I'm trying to read the raw contents of a binary file, so they can be manipulated in memory. As far as I understand, bytes() objects are immutable, while bytearray() objects are mutable, so I read the ...
0
votes
3
answers
181
views
Why can't I reassign variables in this function?
Here is the question:
You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.
Here is my code:
def ...
0
votes
1
answer
81
views
Difference between full variable shallow copying and slice partial copying
From what I understand, Python is a pass by object reference language, which means that if the original value is mutable, every shallow copy will be affected (and vice versa). So, something like:
x = [...