Questions tagged [ownership]

Ownership is a core concept of Rust. The system of ownership is a set of rules that the compiler checks at compile time to manage the memory. DO NOT USE FOR THE FILE OWNER USER AND GROUP IN UNIX SYSTEMS; for that, use [permissions] instead.

Filter by
Sorted by
Tagged with
1 vote
0 answers
25 views

Can I avoid this borrowing issue? [duplicate]

Given the following struct and function implementations: struct Graph { edges : Vec<(usize,usize)>, vertices : Vec<usize> } impl Graph { pub fn new(n: usize) -> Graph { ...
Aresx's user avatar
  • 11
-3 votes
0 answers
24 views

why I can't initialize repository to old project [duplicate]

"fatal: detected dubious ownership in repository" What is this git fetal error? I tried to initialize a git repository to a project I've created some time ago and it gave me this error. It ...
Pramith Edirisooriya's user avatar
0 votes
0 answers
48 views

`particle` does not live long enough & cannot move out of `particle` because it is borrowed

I don't yet fully understand the concepts of Ownership, Borrowing, and Lifetimes in Rust and this is pretty confusing. Basically, I get these two errors when I compile: error[E0597]: `particle` does ...
Keys's user avatar
  • 3
3 votes
1 answer
65 views

What is this rust code to remove duplicates from an unsorted linked list doing on a low-level in the else branch?

I have a linked list: pub struct Node<T> { val: T, next: Option<Box<Node<T>>> } pub struct LinkedList<T> { head: Option<Box<Node<T>>> } ...
Elfen Dew's user avatar
  • 156
1 vote
1 answer
64 views

Unable to bound lifetime in for each loop using str.lines() function

I'm new to rust and i'm building an implementation of the grep command to learn this language. I'm trying to create a function to match the search query in a case insensitive way, but i'm having ...
Alex Licata's user avatar
-1 votes
1 answer
44 views

Rust ownership issue

I want to implement Singly Linked List concept by Rust. However, there is issue when I implement push_front function. Error message is like below. cannot move out of self.head as enum variant Some ...
안태찬's user avatar
0 votes
0 answers
70 views

How to use a share mutable struct field to read and write to in the same method

I'm trying to use a shared Vec3 in my Mat4 struct to do some calculations struct Vec3 { x: f32; y: f32; } struct Mat4 { values: [f32;16]; tmp_vec3: Vec3; } I have this method inside Mat4: ...
hope_is_grim's user avatar
  • 1,934
0 votes
0 answers
58 views

Double linking Rust structs [duplicate]

I am trying to implement a collection of objects where each of its contained objects also has a non-mutable reference to the collection to which they belong. However, I am having trouble finding a ...
Hèctor M.C.'s user avatar
1 vote
1 answer
71 views

Why doesn't (&mut iter).take(n) take ownership of iter? [duplicate]

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=27451eb0a114417afcea5b6c53a92ff2 In this code: fn main() { let my_vec = vec![1,2,3,4,5,6,7,8]; let mut pair: ...
Chowlett's user avatar
  • 46.1k
-1 votes
1 answer
88 views

std::shared_ptr owned by one class and initialized by another class

I have a class lets say A. Class A has a member variable of type: std::shared_ptr<SomeType> m_dataMemberInA I do not initialize the member in Class A. In a class B I also have a std::shared_ptr&...
JamalNewtron's user avatar
0 votes
0 answers
37 views

Why does rust allow us to store mutablre referneces to a immutable variable? [duplicate]

In rust, if we can store mutable reference to a mutable variable, like so: fn main() { let mut str: String = String::new(); // a mutable string let ref1 = &mut str; // storing a mutable ...
Abir Sheikh's user avatar
0 votes
2 answers
53 views

How can a closure outlive the main function if the entire process ends when main function ends?

I have below code: use std::thread; fn main() { let x: &'static mut [i32; 3] = Box::leak(Box::new([1, 2, 3])); thread::spawn(|| dbg!(&x)); } When I compile it, I get below error: ...
Fajela Tajkiya's user avatar
1 vote
2 answers
48 views

impl trait with move method for trait object of same trait

I am trying to implement a trait on a boxed trait object of the same trait. I've done this before for trait whose methods take &self which works fine, but not self. // The purpose of this trait is ...
Max888's user avatar
  • 3,247
1 vote
1 answer
62 views

How to indicate to rust to move a value to another scope?

The following code fails to compile due to the compiler thinking that s remains in the scope of main instead of moving into the scope of spawn. Why doesn't the compiler understand that s doesn't need ...
matanmarkind's user avatar
-1 votes
1 answer
79 views

What is the best way of dealing with a big mutable struct in Rust?

Here is a simplified view of my problem : struct Game { currentPlayer: u8, players: Vec<Player>, units: Vec<Unit>, } fn update(game: &mut Game) { for unit in game....
oui's user avatar
  • 87
0 votes
1 answer
32 views

How to pass impl trait to a thread

I'm trying to pass the handler to a thread for each incoming request, I tried to wrap it inside an Arc but I'm getting the following error: the parameter type impl ConnectionHandler may not live long ...
solomancode's user avatar
-1 votes
1 answer
30 views

Need more explanation in the behaviour of Scope and Drop call in Rust in the context of Ownership

I'm a newbie to Rust and got little more curious to learn its ownership concepts. According to the Official Documentation the following is mentioned regarding concept of referencing: Here is how you ...
Akash R's user avatar
  • 46
0 votes
1 answer
36 views

Rust Reborrowing Shared Reference from Mutable Reference

I'm new to Rust, and trying to understand why a mutable reference to a data structure that has had an element be borrowed can seemingly be used again within the same lifetime to borrow another element....
mishar's user avatar
  • 401
-1 votes
2 answers
72 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....
杨尚山's user avatar
0 votes
0 answers
32 views

Rust: struct with vector of references to another vector of the struct [duplicate]

I defined two structs like these: #[derive(Debug)] struct Slices<'a> { intervals: &'a[u32] } #[derive(Debug)] struct NumbersWithSlices<'a> { numbers: Vec<u32>, ...
MaPo's user avatar
  • 633
0 votes
0 answers
45 views

How is this element valid after some of its members have been consumed by a function call? [duplicate]

First of all: I really find it puzzling that my previous question gets closed and a hint pops up: "when to use drain vs into_iter" - that was not my question at all. So I repeat it here - ...
P.Jo's user avatar
  • 680
0 votes
1 answer
78 views

How can I return a mutable reference to a value owned by the current function

Here is my struct and I need a get_mut function that returns a mutable reference to a value owned either by ctx.scope or ctx.parent.scope recursively pub type RuntimeContext<'c> = Rc<RefCell&...
Sassy's user avatar
  • 40
4 votes
1 answer
55 views

How do I iterate over a vector of strings stored in a struct without moving them?

I have a large struct that has a vector of Strings as a member. I am trying to iterate over these and pass each to another method that takes a &str argument. The latter method requires &mut ...
tetricyclone's user avatar
-1 votes
1 answer
94 views

Map without side-effects? A map that takes ownership (and not a mutable reference) on insert?

Is there a data structure in Rust that would have the following kind of function signatures? impl<K, V> Map<K,V> { fn insert(self, key: K, value: V) -> Self } i.e. It does not take a ...
gust's user avatar
  • 888
0 votes
2 answers
50 views

Rebind a variable to a different type while used in the `match` declaration

I am writing Rust code with a typestate pattern to create an API and a CLI for it. I have a struct VendingMachine<S> where S is a ZST representing my current state (e.g. VendingMachine<Start&...
artemetra's user avatar
2 votes
2 answers
103 views

Returning a &HashMap from rust function

I am struggling to find an elegant to solution to access a nested map for read-only purposes in rust. I have a situation of this kind and ideally as example I could return a reference to an empty map (...
Redirectk's user avatar
  • 171
0 votes
0 answers
22 views

Get a reference to Vector from inside of a struct inside Rc<RefCell<>> [duplicate]

I am trying to implement a Directed Acyclic Graph in Rust, and have two structs defined like this: struct ValueData { val: BaseType, children: Vec<Rc<RefCell<Value>>>, ...
ndsrib's user avatar
  • 3
0 votes
1 answer
49 views

Return ownership from an overloaded operator if Copy trait is unavailable

With a struct that contains a String (thus preventing implementation of Copy trait), if I use the struct with an overloaded operator, I am unable to use the struct variable again (which is expected). ...
ndsrib's user avatar
  • 3
0 votes
0 answers
22 views

reference to non copy object returned by value in Rust [duplicate]

Why can I create a reference to an object created inside a function without first copying it to some variable? Isn't the object dropped at the end of the function? struct MyStruct { one: i32 } fn ...
FeliceMente's user avatar
1 vote
2 answers
153 views

Are there differences between .to_owned(), .clone() and dereferencing (*)?

With this code on the rust playground: fn main() { let a = &[1, 2, 3]; let mut o = a.to_owned(); let mut c = a.clone(); let mut d = *a; o[0] = 7; c[0] = 8; d[...
fadedbee's user avatar
  • 43.1k
3 votes
1 answer
92 views

How does the std::unique_ptr&& function argument work? [duplicate]

I'm writing a simple game engine in C++. I'm very late to C++, because I've spent most of my free time with C, so the unique_ptr, shared_ptr and all of this ownership magic is hardly understandable ...
y3v4d's user avatar
  • 195
0 votes
1 answer
49 views

Take Ownership from retain or reference

I am writing a Rust parser toy, and I want to transform some nodes, there are three possible for this transform remove, keep, ToTopLevel, remove and keep is ok, but when I encounter ToTopLevel, I need ...
steven-lie's user avatar
0 votes
1 answer
56 views

My linked list implementation in Rust won't insert a new element at the end of the list

I am implementing the linked list data structure in Rust to try and learn the language. I was following a tutorial, but I noticed that their implementation inserted an element only at the start of a ...
Piyush's user avatar
  • 3
-3 votes
1 answer
41 views

Variable lifetime problem when passed to message channels within threads in Rust

I'm writing a Rust program that does the following: Create an array of threads to spawn, each holds a variable which stores the path of a directory: let (tx, rx) = mpsc::channel(); let handles: Vec&...
aisuneko's user avatar
0 votes
0 answers
30 views

"Returns a value referencing data owned by the current function" inside match arms [duplicate]

I want to retrieve a reference from a struct wrapped inside an enum. I should not clone or copy the data because i need only to read. From what i understand the problem comes because i'm trying to ...
Paolo Bonomi's user avatar
0 votes
1 answer
67 views

Why does this struct method still borrow the mutable reference?

I am attempting to implement something akin to the Observer pattern in Rust. I have some decent experience with Rust, however I can't specifically pinpoint the reason why the following code has this ...
BlueOyster's user avatar
1 vote
1 answer
61 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<&...
Frank Schwidom's user avatar
2 votes
1 answer
123 views

How Option<&T> implement Copy

I noticed something weird about the map function of Option<&T> and Option<T>, after a quick googling, there is someone else noticed the same issue, as described in this question. I ...
Theodora's user avatar
  • 571
0 votes
0 answers
46 views

Is there a way to have a usable mutable reference or similar to mutable data while still having usable ownership of said data

I'm writing renderer for terminal in Rust and I hit a wall when trying to make something like layer system, but different. I have structs Renderer and Frame with trait CanvasLike pub struct Renderer { ...
Ur-fault's user avatar
0 votes
2 answers
53 views

Why can't I edit these values outside the scope?

I am working on a ray tracer where I need to be able to change certain variables based on input on runtime. I have values such as CamDir and CamPos that need to be changed over runtime but keep ...
Question Asker's user avatar
2 votes
2 answers
262 views

How to REALLY PROPERLY convert mutable reference to immutable reference in Rust?

I've searched about this question before, like this and this, but following the solution of the first link and try to apply them to my code, rustc seems misunderstand what I'm trying to do. I wanted ...
ArchBug's user avatar
  • 45
1 vote
2 answers
70 views

Can I create an immutable vector from another immutable vector in Rust without copying?

I'm new to Rust and write a library for linear algebra on binary matrices. I have a sparse matrix struct storing a matrix in column major format (CscMatrix). The CscMatrix stores the positions of ones ...
Finn's user avatar
  • 37
0 votes
1 answer
54 views

Rust Option Assignment When Implement Listed List

I am practicing Rust by implementing a listed list, when I write the function insert_after, I got a compiler error, but when I use take method of Option, it disappears, I want to know why because i ...
steven-lie's user avatar
0 votes
0 answers
185 views

Rust - move value in hashmap without cloning and keep value in hashmap

I'm using a hashmap as an environment for a tree walk interpreter. This hashmap maps strings to values. Value is an enum that implements the Clone trait but not Copy. The following is a huge ...
dvr's user avatar
  • 370
0 votes
0 answers
41 views

Python: Changing Windows Information Protection file ownership from "work" to "personal"

Everytime when I download a file from my company's SharePoint it changes the Windows Information Protection File Ownership to Work. I can't access the file in Python (Permission denied error). I have ...
Gew00nHarry's user avatar
1 vote
1 answer
230 views

use of moved value: `response` value used here after move for types not implementing the Copy trait

I have this code which is throwing the following error: use of moved value: response value used here after move. use std::collections::HashMap; use reqwest::Response; use serde_json::json; async fn ...
Cizia's user avatar
  • 438
0 votes
0 answers
221 views

Transfering the ownership of a calendar event to another user

I'm trying to create a script to transfer the ownership of a calendar event, created by me, to another user. Actually, I have a script to create a large set of events automatically from a google sheet....
Santiago TORRES ALVAREZ's user avatar
0 votes
1 answer
43 views

Passing a variable so a function recreates it in rust [duplicate]

I'm trying to insert multiple pieces into a hashmap as so fn main() { let mut pieces: HashMap<&str, Piece> = HashMap::new(); for column in b'a'..=b'h' { let column_char:...
Taonga07's user avatar
0 votes
0 answers
121 views

Unity Netcode PlayerObjects empty after spawning on NetworkManager

I'm starting to learn Unity's Netcode for online multiplayer games. I have a simple 2D scene where players can connect and control their own square. That works fine and everything gets synched between ...
Freakwave's user avatar
  • 154
0 votes
0 answers
20 views

Moving local data out of function [duplicate]

I'm pretty new to Rust and struggling with the concepts of ownership. In this example, I'm using SIMD Json for Rust library to parse JSON. It has a concept of parsing "borrowed values" - ...
Alex Abdugafarov's user avatar

1
2 3 4 5
16