Questions tagged [mutable]
A mutable can be modified after it is created.
1,186
questions
0
votes
1
answer
28
views
How to add if then else based on mutable variables in FParsec parsers?
I'm trying to add error recovery to an FParsec parser that consumes a comma-separated sequence in parentheses, e.g. "(a,b,c)".
I came across the following problem: Given the two inputs "...
3
votes
1
answer
106
views
Rust "use of borrowed...." compilation error
I have a list of node
struct ListNode {
val: i32,
next: Option<Box<ListNode>>
}
impl ListNode {
fn new(val: i32) -> Self {
ListNode {
next: None,
val
}
}
}
...
-1
votes
2
answers
67
views
This example subverts my understanding of ownership and reference scope
// print:
// string-a
// string-aaabc
fn main() {
let mut a = String::from("string-");
let s = &mut a;
let ss = &mut a; // s goes out of scope here
ss....
2
votes
3
answers
45
views
Python itertools.zip_longest with mutable fillvalue
In a code that evaluates a web response, I would like to zip elements from several lists. However, the elements of the iterators are dict's.
Therefore, I would like to fill up the missing values also ...
0
votes
0
answers
17
views
python function cache a mutable result
Is there a way to cache a mutable result and prevent the cache being modified after function call?
from functools import lru_cache
import pandas as pd
@lru_cache
def myfun(x):
return pd.Series(...
0
votes
1
answer
32
views
What is the syntax to make a callback function variable mutable in Jetpack Compose?
I'm trying to make the following variable, selectedView, mutable so that I can set the current Composable View dynamically.
var selectedView :@Composable () -> Unit = { testView() }
I'm passing ...
0
votes
1
answer
44
views
why MutableState<Float> is seen as Float when calling the function?
`@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BMI() {
var bmi by remember { mutableStateOf(0.0f) }
var weight by remember { mutableStateOf("") }
var height by remember ...
0
votes
0
answers
16
views
Why a String which by definition is immutable can change its size?
I know that String is immutable which means once created it cannot change its size (can't become larger or smaller) or it cant be changed any of its characters. Now, I found 2 examples and it is a bit ...
2
votes
0
answers
66
views
Using objects with mutable fields inside constexpr functions
A constant expression cannot access a mutable sub-object. This is in expr.const#4.8
An object or reference is usable in constant expressions if it is ... a non-mutable subobject ...
And there is a ...
0
votes
1
answer
349
views
Why do I get a "borrowed data escapes outside of method" error?
I have a variable renderer that I have to edit over an event loop. The issue is that I keep getting the same borrowed data escapes outside of method error for the event loop in the run function of my ...
6
votes
2
answers
139
views
mutable data member, template constructor and trivially copy constructible
Example code could be found below or on godbolt. Say we have 4 classes:
S<T>: holding a data member.
SCtor<T>: holding a data member and has a template constructor.
SCtorMutable<T>...
2
votes
1
answer
127
views
Analogue of `std::pair` with mutable members?
I am implementing analogue of std::map called expiring_map which is based on boost::multi_index::multi_index_container. Idea is simple: when there is new insert to the expiring_map there will be check ...
1
vote
0
answers
26
views
Difference in scope between int and list in Python code [duplicate]
I have the following Python code snippet:
# code 1
# makes an error
def func1():
a += 1
a = 1
try:
func1()
print(a)
except UnboundLocalError as e:
print(e)
# code 2
# makes no ...
1
vote
2
answers
134
views
How to execute an array of tasks sequentially?
I have the following code that I want to review
printfn "calling openai embeddings API"
let sw = System.Diagnostics.Stopwatch ()
sw.Start ()
let embs : MyRedis.RedisEmbedding array =
...
0
votes
0
answers
17
views
How to release a mutable borrow after method call which takes mutable reference to self? [duplicate]
How can I call an objects method which takes a mutable reference to self, without moving the object into the method scope?
The following code shows a very simple struct, which has two attributes 1) a ...
0
votes
2
answers
103
views
Why can a const member function modify an object's mutable data member in C++11? [closed]
Why and how can a const member function modify an object's mutable data member?
Member functions use the this pointer to modify the data members of an object. The this pointer of a const member ...
1
vote
1
answer
94
views
Parameter binding with immutable objects
I have doubts about this Standford University paper (I recommend it, I found it on the Internet), but a question arose about this code:
# parameters are passed via binding
def main():
original = [...
1
vote
1
answer
117
views
cannot borrow as mutable more than once at a time + the variable is a mutable queue
I'm trying to traverse a graph and extract a sub-tree out of it based on the criteria which is defined in my code. The details of the graph or the criteria is not important. However, the process of ...
0
votes
0
answers
25
views
Difference in Rust between '&mut val' and '&mut *ref_to_val', where ref_to_val = &mut val [duplicate]
The following code does NOT compile (which is correct, since there can't be two mutable references to the same value n at the same time):
let mut n=5;
let p1 = &mut n;
*p1 = 10;
let p2 = &...
-1
votes
1
answer
115
views
Avoid "$0' is immutable" on a lazy getter function?
I have a lazy var in my struct called labelColors:
lazy var _labelColors: LabelType = { return url.getTagColors() }()
var labelColors : LabelType {
mutating get { return _labelColors ...
0
votes
0
answers
30
views
Mutable references in rust and `&mut` [duplicate]
So I am reading through The Rust Programming Language book. Specifically, in this section it says the code
scores.entry(String::from("Blue")).or_insert(50);
"returns a mutable ...
1
vote
2
answers
109
views
Design a trait in Rust with a mutable getter and an immutable getter and that implements the immutable getter by default
I want to design a trait with a mutable and an immutable getter to some field of self.
However, I want that the implementer of the trait has to implement only one method, typically the mutable getter.
...
0
votes
1
answer
65
views
Convert web::Json<T> to &mut T
I am trying to write a simple api to create user in actix-web but I need to pass the User object as mutable reference in the method db_connector.create_user() because it needs to be edited behind the ...
0
votes
1
answer
44
views
Python list copy and slice modifying original list
I have a list as shown below:
voting_records = [['1.', 'DIRECTOR', 'Management'],
['1', 'Allison Grant Williams', 'For'],
['2', 'Sheila Hartnett-Devlin', 'For'],
['3', 'James Jessee', 'For'],
['4',...
0
votes
0
answers
47
views
How does passing lists recursively in python work?
I am trying to better understand how passing lists in python works. I have a very strong understanding of C++ so when I taught myself python my understanding was that passing a list is like passing a ...
0
votes
1
answer
43
views
Pandas dataframe mutability with loc method
I am trying to understand the inticacies of using loc on a dataframe. Suppose we have the following:
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
df2 = df.loc[:,'a']
df2.loc[0] = 10
print(df)
print(...
0
votes
1
answer
50
views
I am unable to update to different mutable arrays while processing a big array using par_iter()
A large array of structs to be processed and two different mutable arrays should hold the values.
I used par_iter and got the following error:
fn par_calculate_depreciation_for_assets(...
2
votes
1
answer
67
views
How to get a working mutable reference to a subset of an array?
This works as expected for reading:
fn u64_from_low_eight(buf: &[u8; 9]) -> u64 {
let bytes: &[u8; size_of::<u64>()] = buf[..size_of::<u64>()].try_into().unwrap();
u64::...
2
votes
0
answers
63
views
what happens to a rust mutable value after each assignment [duplicate]
Here are two examples of dynamic mutable value.
pub fn main() {
let mut x = String::from("Hello");
println!("{}", x);
x = format!("{x}, world!");
println!...
1
vote
1
answer
73
views
Are variables obtained by destructuring a tuple mutable?
Does destructuring a tuple make the variable mutable?
This is the code snippet that confuses me:
let tup = ("duck", 11, true);
let (_, data, ..) = tup;
println!("data: {}", data);
...
1
vote
1
answer
90
views
In Rust, what is the idiomatic way to install a mutable callback function on multiple subobjects at the same time?
I have an algorithm that manipulates an array of objects in some manner, but the caller needs to be able to listen to certain events (updates on the objects) triggered by the algorithm.
The following ...
-1
votes
1
answer
30
views
How do i change Python 2d array elements?
new = []
curvepoints = []
for i in range (0, 10):
for j in range (0, 3):
new.append(0)
curvepoints.append(new)
new = []
I have initialized my main array curvepoints using ...
0
votes
1
answer
56
views
why does the property of the external function inherit to the private variable of the javascript function
Try to use functional programming to create an object with external functions to reduce memory usage.
The function is
//increment no of test cases
function incrNoOfTestCases(inputObj){
let hits = ...
1
vote
1
answer
267
views
Mutable reference to parent in tree-like structure
I am developing a Rust program that performs operation on tree structures, let's call them Node. It is not required to store list of child nodes of each node, but it is needed to be able to get back ...
0
votes
1
answer
305
views
Cannot borrow as mutable, getting a mutable reference from a borrowed value [duplicate]
I was following this other post: Understanding Rust `Rc<RefCell<_>>` where op tried implementing a tree with Box and was successful in doing it but then tried implementing it with Rc and ...
0
votes
0
answers
210
views
I want to save and restore a mutableList or array in Kotlin
I have the following mutableList
val rowsSavedList = mutableListOf<Int>()
The data is lost when the app changes from portrait to landscape. I save the rest of my data using onSaveInstanceState ...
0
votes
0
answers
53
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 ...
-1
votes
1
answer
207
views
Rust pushing to vector with borrow_mut
Let's have a struct containing a vector of cities and a new_city function adding City to the vector. However, I got BorrowMutError which makes sense.
What should I do so I can call new_city multiple ...
3
votes
1
answer
193
views
Why do Rust lifetimes break mutable references in loops?
In attempting to refactor a Rust application that was working fine, I tried to separate out the contents of a loop into a new function. However, in this newly refactored out function, I needed to pass ...
0
votes
1
answer
579
views
Kotlin list removeAll is not working with a list
Why Kotlin list removeAll doesnt not work in this example:
orderList.addAll(allProducts)
orderList.removeAll(allProducts)
The code above will add the products but not remove them. orderList is a ...
0
votes
1
answer
145
views
Enum member as a default value on signature
I know that assign a mutable object as a default value on function is bad practice.
Something like:
def foo(a = []):
pass
My question is assign a Enum member is also a bad practice?
Something like:...
0
votes
1
answer
811
views
How to pass a mutable list as a parameter of a function (kotlin)
I am trying to make a function bubbleSort() that takes a mutable list of x(given by user) indexes as a parameter. So far the program is as follows:
The following code cannot be modified:
fun main(args:...
0
votes
3
answers
106
views
Remove duplicate mutable objects from a list
When I have a list of immutable objects, lst and want to get rid of duplicates, I can just use set(lst):
lst = [0,4,2,6,3,6,4,9,2,2] # integers are immutable in python
print(set(lst)) # {0,2,3,4,6,9}
...
-1
votes
2
answers
124
views
Composable function not being executed after mutable value change
So I got this line of code:
fun LiveTrainingScreen(viewModel: LiveTrainingViewModel = viewModel()) {
Column(modifier = Modifier.padding(PaddingStatic.Small).zIndex(2f)) {
//Large Video Display
...
0
votes
2
answers
125
views
Modifying a data of type "static const int* const" from a member function
TLDR Question:
class MyClass
{
public:
void Modify()
{
//How can I modify MyData here
}
public:
static const int* const MyData;
};
Lore:
I have a class like this:
class ...
2
votes
1
answer
265
views
Mutable references rust [duplicate]
fn main() {
let mut x = 42;
let y = &x;
*y = 5;
}
This does not compile. Why does it have to be a &mut to x?
In my understanding, the reference (i.e. address where the value of x ...
0
votes
2
answers
33
views
List non-mutating method
Is there in python any method that instead of mutate the original list it returns a new object?
In JavaScript there is at least one:
const originalArray = [1,2,3]
originalArray.concat(4) // returns a ...
0
votes
0
answers
93
views
Most efficient way to mutate data member
I've been wondering about this question for a long time. What is the most idiomatic and / or efficient way to assign a new value to a data member (mutation)? I can think of 3 options:
Mutate directly ...
1
vote
1
answer
80
views
Python updating list from constructor by object.attribute
If a class is created with the attributes: name and list and the name attribute has a default value and the list is appending the name. Is it possible in somehow when I create an object "a" ...
0
votes
0
answers
50
views
I see inconsistent behavior with Android Compose and Mutable objects (newbie?)
I need help with composables and mutableStates!
In the example below, I have a list of classes.
I want to try to manipulate the list to
a. swap the position of two items
b. change the "data" ...