1,220 questions
1
vote
2
answers
108
views
Modify a mutable vector in chunks
I am very new at the ST monad, and have reached my wits end in trying to correct the error in the code below.
I have a buildChain function, which we can assume works, takes an Int and returns a list ...
0
votes
1
answer
84
views
Value of a mutable variable is not updated in XUnit test
I wrote an XUnit test in F# for a function that updates a mutable variable:
[<Fact>]
let ``UpdatePlayerOneAmountTests`` () =
//-- Arrange
let input = new StringReader "10"
...
2
votes
1
answer
67
views
Strange behavior when partitioning list of tuples into different lists [duplicate]
I found some really unexpected behavior today using python 3.12.4. I am trying to sort a list of tuples into 2 different lists in a list of lists based on the first number of the tuple. Instead, each ...
2
votes
2
answers
112
views
Lambda static vs mutable variable
I have encountered a lambda with static variable in the following answer https://stackoverflow.com/a/79631994/2894535 :
EXPECT_CALL(my_mock, foo(_))
.WillRepeatedly(InvokeWithoutArgs([](){
...
0
votes
0
answers
32
views
Nested mutable and immutable borrows in rust [duplicate]
MRE:
enum MRE_Enum {
variant1,
variant2,
}
struct MRE_Struct {
dummy1: Vec<MRE_Enum>,
dummy2: isize,
}
// Private functions together
impl MRE_Struct {
fn foo(&mut self) ...
2
votes
4
answers
157
views
Getting a mutable element from a std::set, for operations that won't break the order
I've got a data type that consists of actual data and an id:
struct Data {
int value;
int DataId;
};
I've got a collection of these data from which I have to frequently get an element based ...
2
votes
0
answers
62
views
Why does Rust scope include the else of an if conditional as well? [duplicate]
I have the below min repro application which is meant to build a graph (tree) from a vec (split string). (It is meant to be part of a larger loop that would modify the graph/tree multiple times.)
The ...
0
votes
0
answers
24
views
Making nested lists Vs making nested sets (without frozensets)
If I wanted to make a nested set:
nested_set = {{1, 2, 3}, {6, 4, 5}, {12, 8, 5, 7}}
It would give the error: TypeError: unhashable type: 'set'
However if I wanted to make a nested list:
nested_list =...
2
votes
0
answers
100
views
Assign to an expression
I'm learning Rust so getting to grips with mutable and non-mutable. I've copied code from several projects and it works well.
This is the ode_solver function for a two-pool compartmental model. My ...
0
votes
0
answers
37
views
In Unity with C# 8, how to use reflection to set a mutable field value? [duplicate]
Here is a simple example:
[System.Serializable]
public struct PlayerData
{
public string name;
public int level;
public float health;
}
[Test]
...
0
votes
1
answer
88
views
Start a forever thread with a expired objects loop, removing those objects, in rust
I am writing a service, and I want to run a loop forever that checks for some expired objects and removes them if too old.
pub struct Obj {
expired: NaiveDateTime,
}
pub struct Maintainer {
...
0
votes
1
answer
134
views
How to update a collection inside a struct in rust?
Probably this question already has been asked, maybe with different wording, but I couldn't find it. If this gets closed due to this, apologies, but I did try before.
In fact, the problem is simple:
...
1
vote
1
answer
104
views
Does a mutable reference means an ownership loss in Rust?
This exercice from Rustlings, once corrected, gives:
fn move_semantics4() {
let mut x = Vec::new();
let y = &mut x;
y.push(42);
let z = &mut x;
z....
-1
votes
1
answer
71
views
Python List NOT modifying in place while splicing?
I have a list of chars. I want to insert a string in between the chars at given index.
For that I wrote a function to insert the item (string) in the list in-place. The list inside the function is ...
2
votes
2
answers
142
views
Is Python function immutable?
I have
import copy
class A:
_member_a: dict[str, str]
_member_b: Callable
def set_b(self, func):
self._member_b = func
def deep_copy(self):
return copy.deepcopy(self)
I ...
0
votes
0
answers
51
views
Function adapting to mutable or non-mutable input
I wanted to build a function/method that could adapt if a non-mutable or mutable reference was provided.
I tried something like this (playground):
trait TryAsMut<'a, T> where T: 'a {
fn ...
0
votes
1
answer
86
views
Best way to have a nested mutable data element in rust
I'm trying to figure out the best way to handle some nested mutable changes. I've got the following code that mimicks the issue I'm running into:
use std::collections::HashMap;
use circular_buffer::...
0
votes
1
answer
125
views
Kotlin backing field wrong type
ViewModel
private val _wordPressPostsState = Channel<WordPressPostsState>()
val wordPressPostList: List<WordPressPostDataDomain>
field = mutableListOf<WordPressPostDataDomain>()
...
0
votes
1
answer
175
views
How to use Kotlin backing field with Channel and Flow?
I am playing with the new backing field feature introduced in Kotlin 2.0, however I am encountering some problem when using it on data type that is not a superclass/subclass of one and another.
...
3
votes
1
answer
127
views
Why does `Option::map` work with immutable data, but not with mutable data
Why does the immutable version in the following example work, but the mutable version does not compile with error error: lifetime may not live long enough?
trait Car {
fn honk(&self);
}
...
0
votes
1
answer
174
views
Can I Prove Monotonicity of Allocations to the Rust Borrow Checker
I have the following code which does not compile:
// TODO: Return Result, remove `.expect`s
fn to_blender_subfile<'a>(
filepath: &str,
transform: Transform,
visited_file_cache: &...
1
vote
1
answer
856
views
How to use Rust OnceLock get_mut() method?
The Rust documentation has a OnceLock::get_mut method that returns a mutable reference. But the following code does not compile. What am I missing?
use std::sync::OnceLock;
#[derive(Clone)]
struct ...
0
votes
1
answer
118
views
Bad design for Rust program with lifetime and multiple references
I am implementing a graph data structure in Rust. For each node (and also edges - omitted from this snippet) in the graph I have a struct Algorithm (perhaps poorly named) that performs some node and ...
-1
votes
1
answer
83
views
How to avoid second borrow in rust when iterating over mutable member of a struct and changing other members [duplicate]
I'm trying to write a code which borrow a mutable copy of the last member of a vector and then change another member of the vector. There is a check that the vector has more than 2 elements so there ...
0
votes
0
answers
205
views
making a Vec<Child> containing reference to Parent struct? [duplicate]
Im new to Rust, and i'm having this problem where I need to keep a Vec of Child in the Parent struct, and each child needs to be able to use the Parent functions, so with some research I ended up with ...
0
votes
0
answers
45
views
Cannot borrow variable as mutable within loop [duplicate]
I have the following file in my interpreter for a personal programming language. The program itself is meant to take the output of the parser and convert it into an active parse tree.
use crate::...
0
votes
1
answer
197
views
Two-way mutable pointer relationship with trait DerefMut in a container-element setup?
I am trying to implement something which Rust's ownership rules almost seem designed to make impossible. But it's very simple: I want a framework containing a hashmap where the values are a class, ...
1
vote
1
answer
68
views
Abstracting mutable/immutable references in rust
I need to get rid of duplication in this code:
pub struct Memory {
layout: MemoryLayout,
rom: Vec<u8>,
ram: Vec<u8>,
}
impl Memory {
pub fn get_mem_vec_ref(&self, ...
-1
votes
1
answer
343
views
Exposing an Immutable and Mutable Record Class C#
I would like to write a set of c# record classes that offer both a Immutable and Mutable version of themselves.
This is similar to how there is a List and ReadOnlyList offered in c# (yes, arguably not ...
0
votes
0
answers
191
views
How to resolve mutable borrow followed by immutable borrow within a loop in Rust?
I'm encountering a borrow checker issue in Rust where I am attempting to modify a Vec<u8> within a loop using splice, and then obtain a reference to the same Vec immediately afterwards. The ...
3
votes
1
answer
112
views
Lifetime when exchanging reference
I'm learning Rust and play through some scenarios to see how it behaves. When passing a mutable reference to a function and then assign another mutable reference to it, it seems like the Rust compiler ...
0
votes
0
answers
65
views
How to Implement a Const Function in C++ that Calls a Non-Const Update Function Without Making Class Variables Generally Mutable? [duplicate]
I am working on a C++ project where I have a specific design challenge and I'm looking for advice on best practices. Here's the situation:
I have a class with a member function that I want to keep as ...
1
vote
2
answers
112
views
How to count the number of filtered elements in a chain of iterator adapters
I have a chain of iterator adapters (which I don't know the number of at compile time) applied to an initial iterator.
A simplified example would be to filter a range of numbers by their divisibility ...
0
votes
0
answers
130
views
In Rust, why do we need to specify a reference variable is mutable each time we change its value?
In the following guessing game, from the Rust Book, why do we have to say that the reference to the variable .read_line(&mut guess) is mutable since we already stated it was mutable in a previous ...
2
votes
0
answers
61
views
Why do mutable borrow errors disappear when refining the type of a function pointer variable
In my function I need to rotate a VecDeque a certain amount of times, always in the same direction that depends on the input, with a value that never changes. So I started envisioning a solution like ...
2
votes
1
answer
624
views
Non-state variable inside SwiftUI View
I just rewatched Demistify SwiftUI and noticed that some of the examples use variable properties inside a SwiftUI View, without using the @State property wrapper. For example (around 19.04):
struct ...
1
vote
2
answers
303
views
const_cast vs mutable and undefined behavior
Edit: I edited the code here to not use pointers because there were too many unrelated comments about it
#include <iostream>
struct Foo {
Foo(const int a) : total(a) {}
int index ...
0
votes
1
answer
187
views
Store an object in a static Box and then retrieve as mutable?
This is a PyO3 situation. So the Python calls a long-running task. Using ZeroMQ messaging (inter-process messaging*) it is possible for the user to order the task to be suspended. At that point I want ...
0
votes
2
answers
306
views
Call a function that uses `&mut self.0` in a loop (E0499)
I'm looking for a way around the lack-of-polonius problem in this specific circumstance. The other answers seem inapplicable, as far as I can understand at the moment.
I have two structures, ...
1
vote
1
answer
229
views
What does target and object mean in assignment statements?
https://docs.python.org/3/library/copy.html#module-copy
Assignment statements in Python do not copy objects, they create
bindings between a target and an object. For collections that are
mutable or ...
3
votes
1
answer
1k
views
How to pass a struct implementing multiple traits to a function accepting those traits as &mut?
I'm dealing with a problem that can be simplified to the following code. The result is error[E0499]: cannot borrow *dog as mutable more than once at a time..
The origin of the error is clear to me, ...
0
votes
1
answer
598
views
Nushell table update works unless I set the result to a mutable variable
This code runs perfectly:
$table | update col { |row| "some value" } | print
This code also runs perfectly:
let $final_table = $table | update col { |row| "some value" }
...
0
votes
1
answer
51
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
258
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
97
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
135
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
1
answer
517
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
441
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 ...
2
votes
0
answers
111
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 ...
3
votes
1
answer
11k
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 ...