Questions tagged [mutability]
Mutability is property of any function, variable or expression whose values are subject to changes with "side-effects". In other words, the value does not have referential transparency.
304
questions
2
votes
1
answer
62
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
53
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
48
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
73
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
68
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
22
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
41
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
44
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 {
...
0
votes
0
answers
41
views
What is the point of immutable variables if I can redeclare it? [duplicate]
The rust book comes with this example.
https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html
let spaces = " ";
let spaces = spaces.len();
So then the variable has not only ...
1
vote
2
answers
274
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
37
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
48
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
82
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
98
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
56
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. (...
1
vote
1
answer
1k
views
Efficient way to update a single element of a Polars DataFrame?
Polars DataFrame does not provide a method to update the value of a single cell currently. Instead, we have to the method DataFrame.apply or DataFrame.apply_at_idx that updates a whole column / Series....
0
votes
1
answer
53
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
60
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
27
views
Javascript: Why does setting two immutable variables equal pass the '===' test, but immutable not? [duplicate]
let a = "hello"
let b = "hello"
console.log(a === b)
returns true, but
let a = ["hello"]
let b = ["hello"]
console.log(a === b)
returns false. Why is this?
0
votes
0
answers
52
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
143
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
...
0
votes
1
answer
201
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
68
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
66
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
35
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
144
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
365
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
77
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
174
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
110
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
21
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
28
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
145
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
133
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
339
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
60
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
195
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
475
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
157
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
57
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 = [...
0
votes
1
answer
57
views
Why is a stored function in an object property being overwritten (Python)?
The following is a minimum working example of my problem where I have a school object containing an array of fish objects, and I want each fish to have properties based on their index. All I'm doing ...
0
votes
4
answers
336
views
Can I link two variables such that one is double of another in python?
So basically I have two lists a and b and have defined them like a=b=[10] so changing one will change the other-
a=b=[10]
a[0]+=1
a
>>>[11]
b
>>>[11]
Is there a way to do this but ...
5
votes
1
answer
274
views
How to access mutable iterables inside a nested loop
Every now and then, I run into the same issue with borrowing (or not borrowing) mutable variables inside a loop, and I finally sat down and compiled a minimal example. As a result, the code is a ...
0
votes
1
answer
69
views
the inplace parameter in pandas how it works?
in pandas the inplace parameter make modification on the reference but I know in python data are sent by value not by reference i want to know how this is implemented or how this work
2
votes
1
answer
337
views
How to avoid linking of objects in a list?
My problem is quite simple but I am unable to solve it. When I insert objects into a list, the elements of the list all change whenever I change one of them (they all point to the same object in the ...
2
votes
1
answer
866
views
Does Typescript allow mutations that break type safety?
In the following snippet, is it demonstrated that Typescript cannot warn against mutation of strictly typed objects in a way that violates the constraints of its type?
type Animal = {
name: 'cat'
...
1
vote
1
answer
323
views
Why mutable lists of different types behave as immutable when put inside a mutable list
As we know, it is possible in Kotlin to create a mutable list of mutable lists of different types, e.g.:
val list = mutableListOf(
MutableList<Int>(3) { 0 },
MutableList&...
1
vote
2
answers
86
views
Pattern Matching does not allow me to change values
so I am currently working on a new programming language tr-lang
and I am currently in the process of writing the parser of the language
this piece of code is where the bug lies
BlockToken::İse(bip) =&...
0
votes
1
answer
161
views
Making variable sized immutable list in Kotlin
I try to make a variable sized immutable list in Kotlin, but the only way I found is this. Isn't there a more clean way to do it ?
val size = nextInt(0, 50)
val list = mutableListOf<Post>()
for (...