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.

Filter by
Sorted by
Tagged with
0
votes
0answers
6 views

Symbolic link file ownership is root always in portworx storage

I have a Linux machine where portworx volume is mounted with nfs4. The exports file contents on the machine where portworx volume created is /var/lib/osd/mounts/engsharevol *(rw,...
0
votes
0answers
25 views

Creating a collection of types that implement a trait with generic type parameters [duplicate]

I'm building program that will take circuit of logical gates and evaluate the circuit. I made trait for a logical gate which has methods to get the output value and register and unregister inputs (...
1
vote
1answer
35 views

docker ADD --chown bug or feature?

I am having a problem adding a file to an image and setting ownership via --chown flag. Specifically, here is a dockerfile adding a simple text file: FROM fedora:24 ARG user_name=slave ARG user_uid=...
0
votes
1answer
66 views

“Operation not permitted” from docker container logged as root

I need your help to understand my problem. I updated my macintosh with Catalina last week, then i updated docker for mac. Since those updates, i have ownership issues on shared volumes. I can ...
1
vote
1answer
46 views

Rust Destructors and ownership

I almost asked the same question the other day but in context of c++. I try to replicate destructors and constructors in my c programming. That means for every object or struct there is an ...
2
votes
1answer
85 views

C++ Destructors and Ownership

I try to replicate C++ destructors and constructors in my c programming. That means for every object or struct there is an initialization function and a destruct function which frees all of the ...
1
vote
1answer
45 views

Difference between Iterating over BTreeMap and &BTreeMap

I am trying to understand the difference between let rows = Vec::new(); for (k, v) in my_btree { // BTreeMap<i64, String> rows.push((&k, &v)) // k and v don't live long enough. } ...
0
votes
1answer
66 views

what is the difference between these lines in RUST?

what is the difference between these two scenario I have the same functionality with 2 different model and it is a bit confusing for me ! //model_1 let mut my_str = String::from("ali"); let str1 = &...
0
votes
1answer
50 views

Performing operations on immutable borrow when iterating using mutable iterator [duplicate]

Here is a simple artificial example to illustrate the problem: fn sum_slice(v: &[i32]) -> i32 { v.iter().sum() } fn sum_previous(v: &mut [i32]) { for (i, val) in v.iter_mut()....
1
vote
1answer
56 views

What is the best way to reuse a borrowed struct field if it doesn't implement the Copy or Clone trait?

I am writing a client for a TCP server use std::net::TcpStream; use std::io::{Read, Write, Error}; pub struct Client { addr: String, conn: Option<TcpStream>, } impl Client { pub ...
1
vote
1answer
66 views

Matching with Rc<RefCel<T>>

Consider the following code - which compiles and works: use std::rc::Rc; use std::cell::RefCell; use crate::Foo::{Something, Nothing}; enum Foo { Nothing, Something(i32), } fn main() { ...
1
vote
0answers
49 views

Insert value into `HashMap` and get reference to that value [duplicate]

We have a simple pattern of "get or create" which I was able to implement as shown below. However, we couldn't find an efficient way to avoid this insert followed by get of the value which we just ...
3
votes
1answer
98 views

Why returning a reference owned by the current function is allowed in Rust?

I am learning Rust's lifetime/ownership concepts, and would like to explain the following behavior in Rust (rustc 1.37.0). For a program like this: #[derive(Debug)] struct Book { price: i32, } ...
3
votes
0answers
88 views

Why does modifying a mutably borrowed variable and keeping it unused not throw an error [duplicate]

I have a piece of sample code here let mut s1: String = String :: from("Hello 2"); let s2 = &mut s1; println!("This is s2: {}", s2); s1 = s1 + "World"; //println!("This is s1 : {} and s2: {}",s1,...
0
votes
0answers
48 views

Returning &String vs &str from immutable accessor in Rust

I am designing a simple struct which groups multiple pieces of owned data together. Once the data is inside the struct, I don't want to expose it to mutation. One of the fields of this struct is a ...
1
vote
1answer
58 views

How to run for loop on elements of a vector and change the vector inside the for loop and outside the for loop in rust?

I am new to Rust. I need to create a vector before a for loop. Run for loop on it. Change the vector inside the for loop. Then Change the vector after the for loop. I tried the following code and ...
2
votes
2answers
99 views

A vector is created inside an if block in Rust. How to use it after the scope of if ends?

I am learning Rust. I am trying to calculate a list of prime numbers up to some number. For that I need to create a vector (vec1) inside an if block and use it outside the scope of the if. I tried ...
1
vote
2answers
71 views

How to move non-Copy data between enum items

I have a Rust enum that represents a state machine. I need to move some data between states (where the data doesn't implement Copy). What's a good approach to use? Basically, I'd like to eliminate ...
0
votes
1answer
59 views

Is there any way to clone a reference type into an owned type? [duplicate]

I have a method that I want to return an owned copy of an element. I can justify why I want this if needed. Here is a minimal reproducible example: (playground) use std::collections::HashMap; ...
3
votes
1answer
73 views

Is there any mechanism to generate an “ownership tree” visualization with Rust or the Rust tooling?

In Chapter 4 of "Programming Rust" by Jim Blandy & Jason Orendorff it says, It follows that the owners and their owned values form trees: your owner is your parent, and the values you own are ...
0
votes
1answer
25 views

How do I turn a glob::GlobError into an io::Error in Rust?

I have a glob::GlobError from the glob crate. There's an underlying io::Error that I need. How do I get it? There's a few methods available, such as this one: fn error(&self) -> &io::Error ...
-2
votes
1answer
41 views

How to handle passing a mutably borrowed struct to function closure?

I am using the proptest crate to run some property tests in a no_std environment. proptest's default test_runner::TestRunner::run() implementation takes some input (as a Strategy or ValueTree object ...
3
votes
1answer
184 views

How to take ownership of a C pointer in Rust and drop it appropriately?

I'm calling a C constructor function keyNew that allocates memory for a Key struct and returns a *mut Key to the Rust side. Is it appropriate to use Box::from_raw to wrap the pointer and take ...
4
votes
1answer
152 views

In Rust, can you own a string literal?

According to The Rust book: Each value in Rust has a variable that’s called its owner. There can be only one owner at a time. When the owner goes out of scope, the value will be dropped. According ...
2
votes
1answer
48 views

Moving ownership to a std::io::Chain

I have a Reader that I want to prepend some bytes to, creating a Chain. Ideally I'd want to do this: use std::io::{Chain, Read}; fn thingify<R: Read>(r: R) -> Chain<[u8; 3], R> { ...
1
vote
2answers
132 views

Lifetime of a Google Apps script with no owner?

I have a Google Apps script that belonged to a former colleague. They have been offboarded and the script currently has No Owner. I am curious how long this GScript will exist without an owner ...
1
vote
2answers
49 views

How can I check who created a Docker image?

As in the subject, how can I check who created a certain docker image? When I check docker images i don't get this information. Thanks.
0
votes
1answer
42 views

how to replace member of a structure using this member's method which consume this member itself? [duplicate]

I have a enum, which may contains a vector. And I implement a method for the enum, which can generator a new enum which reuse the same vector in previous enum (I don't want to copy the vector). After ...
0
votes
0answers
35 views

rust function returns re-borrowed reference creates multiple mutable reference [duplicate]

based on https://www.reddit.com/r/rust/comments/46qwjv/why_can_i_use_an_mut_reference_twice/ function returns a re-borrowed reference actually compiles // rustc version = rustc 1.35.0 (3c235d560 ...
2
votes
1answer
69 views

How can I make a range of values using BigInt or BigUint in Rust?

I would like to loop through a range of values that have a BigUint type (from the num crate). How can I do this? I tried for i in 0..a {...} where a is a (borrowed) BigUint type. I got a error ...
4
votes
5answers
165 views

C++ ownership of a function parameter

I wrote a function which has this form: Result f( const IParameter& p); My intention is that this signature will make it clear that the function is not taking ownership of the parameter p. ...
0
votes
2answers
119 views

How to return when ref and ownership transfer both won't work

so, if I return this self.string_ref.unwrap().as_ref() compiler will say error[E0515]: cannot return value referencing temporary value returns a value referencing data owned by the current function ...
1
vote
0answers
54 views

How can one struct own both a sequence and an iterator on the sequence? [duplicate]

I am trying to construct a Defiler struct that owns a fixed sequence and an internal state describing current position within this sequence. The idea is that it can be iterated upon, but sometimes be ...
0
votes
0answers
59 views

How can I give names to Rust slices without taking ownership?

In the context of a crypto problem, to decrease verbosity, I'm "naming" a slice of v as block, doing some stuff to it, but then trying to verify the result of do_stuff on the whole of v: fn x() { ...
2
votes
1answer
77 views

Using an iterator as an argument to a function multiple times from one vector

I'm trying to write some Rust code to decode GPS data from an SDR receiver. I'm reading samples in from a file and converting the binary data to a series of complex numbers, which is a time-consuming ...
-1
votes
1answer
70 views

How can I return a reference to a sub-element of a nested entry in a structure?

I have structure with a vector of other structures: pub struct StructB { value1: u64, value2: String, } pub struct StructA { array: Vec<StructB>, } StructB is constant; during the ...
1
vote
1answer
46 views

Issues with Rust timelines and ownerships

I am trying to create a hashmap by reading a file. Below is the code that I have written. The twist is that I need to persist subset_description till the next iteration so that I can store it in the ...
0
votes
0answers
65 views

Move variable into thread closure

I'm trying to figure out how to solve this issue where I'm using structopt to access commandline parameters and then pass them on for further processing: fn main() { let opt = Opt::from_args(); ...
0
votes
0answers
58 views

Convert from HashMap<String, Type> to &[Type] [duplicate]

I am yet another beginner in Rust who have trouble converting between my types. It boils down to that I have a HashMap<String, Type> and &[Type] as input to another function. The doesn't ...
0
votes
0answers
45 views

Idiomatic Creation Of Wrapped LMDB Cursor Iterator

I'm having some trouble creating an Iterator to wrap around an LMDB Iterator and Transaction in rust. I'm using the lmdb crate which wraps around the C LMDB bindings and can't seem to find a way to ...
1
vote
3answers
153 views

Why can I return a reference to an owned value of a function?

In chapter 19.2 of The Rust Programming Language, the following example compiles without any error. I found out from issue #1834 that there is a new lifetime elision rule that implicitly makes 's ...
-2
votes
1answer
76 views

Is there a way to create a Box from a Vec<u8> that implements the Read trait?

I'm writing a piece of code that using the lopdf crate writes a PDF on a Vec. Then I want to print the PDF via the IPP crate but it requires a Box that I'm not able to create I've tried many things, ...
1
vote
0answers
99 views

What is the correct way to get values via a method without moving it? [duplicate]

I don't understand why Rust moves the value. Do I oversee a major point in the ownership? The struct MyData is a smaller version. I store some values in this struct, and want to access the stored ...
0
votes
0answers
164 views

Can't read input in a loop and convert to Vector in Rust [duplicate]

I'm trying to do this simple assignment from The Rust Programming Language: Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a ...
1
vote
0answers
66 views

I can't get ownership of a value out of a function [duplicate]

I defined a recursive function that creates a tree-like structure from another. The value created inside the function can't get out. I've tried different ways of getting ownership out of the function,...
0
votes
3answers
223 views

What is the meaning of the error “left-hand of expression not valid”?

I wrote this code to see what happens when I pass two strings to a function and return them back again: fn main() { let mut s3 = String::from("hello"); let mut s4 = String::from("wolrd"); ...
-1
votes
1answer
80 views

Understand the design decision of ownership in Rust [closed]

I am trying to understand the usage of ownership in Rust. So from what I can understand, ownership is a runtime mechanism which enforces the programmers to think further and prevent some unexpected ...
2
votes
2answers
261 views

How to extract elements of a vector of strings in Rust?

Let's say I have the following code: fn extract() -> Vec<String> { let data = vec!["aaa".to_string(), "bbb".to_string(), "ccc".to_string()]; vec![data[0], data[2]] } In practice, I ...
0
votes
0answers
30 views

let data = data; to change mutability [duplicate]

I am sometimes tempted to write *** fn main() { // Initialize as mutable. let mut data = String::new(); // ... data.push_str("data progressively built up"); // ... // Move ...
2
votes
1answer
265 views

How can one force Rust to take ownership of memory allocated other than by its safe methods?

In his February 2018 note titled "Memory Safety in Rust: A Case Study with C", Will Crichton wrote: Rust provides the ability to take ownership of raw pointers, which we do using slice::...