Mutable Structs Fields

I know that mutable fields have been removed in 0.6. I get the following error with this code,

C: \ Users \ mflamer \ Dropbox \ Rust \ Tests \ gmap.rs: 23: 8: 23:18 error: assignment to an immutable field C: \ Users \ mflamer \ Dropbox \ Rust \ Tests \ gmap.rs: 23 dart.alpha = vec :: from_elem (self.n + 1, dart);

What am I doing wrong here? Thanks.

pub struct GMap<T> { priv n: uint, priv darts: ~[Dart<T>] } struct Dart<T> { alpha: ~[@Dart<T>], embed: ~[@T], tagged: bool } impl<T> GMap<T> { pub fn new(dim: uint) -> GMap<T> { let mut map: GMap<T> = GMap{n: dim, darts: ~[]}; return map } pub fn new_dart(&self, ) -> @Dart<T> { let mut dart = @Dart{alpha: ~[], embed: ~[], tagged: false}; dart.alpha = vec::from_elem(self.n + 1, dart); //dart.embed = vec::from_elem(self.n + 1, ); return dart; } pub fn dim(&self) -> uint { self.n } } //pub fn traverse(&self,[bool,..]) enum Cell { Null, Vertex, Edge, Face, Solid } fn main() { let topo: GMap<Cell> = GMap::new(3); } 
+4
source share
1 answer

The problem is how variability is inherited through ownership. For something to change, its owner must be changeable. Property is inherited, with the exception of the new owner, while @ and & classified as owner. Thus, in this case, you have a dart to which the @Dart field @Dart , but not the content of the field, so mut on x does not mean that the content of the field is changed (indeed, it cannot be mutable, because otherwise it can change under kicking something else that applies to him).

A way around this is to either make the field a mutable field so that the owner of the dart structure changes, i.e. @mut Dart { .. } (it has a (small) runtime, and can lead to a program crash if it is mutated, borrowed as unchanged), or build it at a time. The former is not optimal, and the latter is difficult to achieve. However, the first may look like this:

 struct Dart<T> { alpha: ~[@mut Dart<T>], embed: ~[@T], tagged: bool } // ... pub fn new_dart(&self, ) -> @mut Dart<T> { let dart = @mut Dart{alpha: ~[], embed: ~[], tagged: false}; dart.alpha = vec::from_elem(self.n + 1, dart); //dart.embed = vec::from_elem(self.n + 1, ); return dart; } 

(What is required for the decision is not @mut "bind the node" , but it is not clear to me how to make it work in Rust.)

+5
source

Source: https://habr.com/ru/post/1484001/


All Articles