borrowing

“cannot move out borrowed content” when assigning a variable from a struct field

强颜欢笑 提交于 2020-02-15 08:28:12
问题 I'm learning Rust and I'm fighting against the borrow checker. I have a basic Point structure. I have a scale function that modifies all the coordinates of the point. I would like to call this method from another method named convert : struct AngleUnit; struct Point { x: f32, y: f32, z: f32, unit: AngleUnit, } fn factor(_from: AngleUnit, _to: AngleUnit) -> f32 { 1.0 } impl Point { pub fn new(x: f32, y: f32, z: f32, unit: AngleUnit) -> Point { Point { x, y, z, unit } } fn scale(&mut self,

How can I do a mutable borrow in a for loop?

此生再无相见时 提交于 2020-02-02 05:39:39
问题 I tried: let mut vec = [1,2,3]; for mut x in &vec { *x=3; } for mut &x in &vec { x=3; } for mut *x in &vec { x=3; } for mut x in mut &vec { *x=3; } for mut x in &(mut vec) { *x=3; } None of these work; how should I do it? 回答1: You may want to re-read The Rust Programming Language section on mutability: You can also create a reference to it, using &x , but if you want to use the reference to change it, you will need a mutable reference: let mut x = 5; let y = &mut x; fn main() { let mut array

String equality in Rust: how does referencing and dereferencing work?

送分小仙女□ 提交于 2020-01-30 04:43:29
问题 As a Rust newbie, I'm working through the Project Euler problems to help me get a feel for the language. Problem 4 deals with palindromes, and I found two solutions for creating a vector of palindromes, but I'm not sure how either of them work. I'm using a vector of strings, products , that's calculated like this: let mut products = Vec::new(); for i in 100..500 { for j in 500..1000 { products.push((i * j).to_string()); } } For filtering these products to only those that are palindromic, I

Cannot move out of borrowed content for a struct

僤鯓⒐⒋嵵緔 提交于 2020-01-17 12:27:09
问题 I'm trying to implement deserializer for a BERT data which comes from an another program via sockets. For the following code: use std::io::{self, Read}; #[derive(Clone, Copy)] pub struct Deserializer<R: Read> { reader: R, header: Option<u8>, } impl<R: Read> Read for Deserializer<R> { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.reader.read(buf) } } impl<R: Read> Deserializer<R> { /// Creates the BERT parser from an `std::io::Read`. #[inline] pub fn new(reader: R) -

How do I write a rust function that can both read and write to a cache?

时光毁灭记忆、已成空白 提交于 2020-01-16 14:39:48
问题 Original Problem Statement I'm trying to write a function that can both read and write from a cache, but I'm running into a problem where the compiler says I can't both mutably and immutably borrow the cache. I've read through https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html , https://naftuli.wtf/2019/03/20/rust-the-hard-parts/ and random stack overflow/Reddit posts, but I can't see how to apply what they say to this code. use std::collections::HashMap; struct

Is it undefined behavior to do runtime borrow management with the help of raw pointers in Rust?

…衆ロ難τιáo~ 提交于 2020-01-14 19:50:51
问题 As part of binding a C API to Rust, I have a mutable reference ph: &mut Ph , a struct struct EnsureValidContext<'a> { ph: &'a mut Ph } , and some methods: impl Ph { pub fn print(&mut self, s: &str) { /*...*/ } pub fn with_context<F, R>(&mut self, ctx: &Context, f: F) -> Result<R, InvalidContextError> where F: Fn(EnsureValidContext) -> R, { /*...*/ } /* some others */ } impl<'a> EnsureValidContext<'a> { pub fn print(&mut self, s: &str) { self.ph.print(s) } pub fn close(self) {} /* some others

Confusion about Rust HashMap and String borrowing

女生的网名这么多〃 提交于 2020-01-05 03:04:52
问题 This program accepts an integer N, followed by N lines containing two strings separated by a space. I want to put those lines into a HashMap using the first string as the key and the second string as the value: use std::collections::HashMap; use std::io; fn main() { let mut input = String::new(); io::stdin().read_line(&mut input) .expect("unable to read line"); let desc_num: u32 = match input.trim().parse() { Ok(num) => num, Err(_) => panic!("unable to parse") }; let mut map = HashMap::<&str,

Confusion about Rust HashMap and String borrowing

好久不见. 提交于 2020-01-05 03:04:42
问题 This program accepts an integer N, followed by N lines containing two strings separated by a space. I want to put those lines into a HashMap using the first string as the key and the second string as the value: use std::collections::HashMap; use std::io; fn main() { let mut input = String::new(); io::stdin().read_line(&mut input) .expect("unable to read line"); let desc_num: u32 = match input.trim().parse() { Ok(num) => num, Err(_) => panic!("unable to parse") }; let mut map = HashMap::<&str,

“if” statement gets executed when the condition is “false” in a Rust program, how to understand it?

送分小仙女□ 提交于 2020-01-02 22:41:28
问题 For the following Rust program: fn main() { let foo = "test".to_string(); if false { let _bar = foo; // value moved to _bar } println!("{}", foo); } I got this error when run it: error[E0382]: borrow of moved value: `foo` --> src\main.rs:6:20 | 2 | let foo = "test".to_string(); | --- move occurs because `foo` has type `std::string::String`, which does not implement the `Copy` trait 3 | if false { 4 | let _bar = foo; // value moved to _bar | --- value moved here 5 | } 6 | println!("{}", foo);

How can multiple threads share an iterator?

℡╲_俬逩灬. 提交于 2020-01-02 09:12:24
问题 I've been working on a function that will copy a bunch of files from a source to a destination using Rust and threads. I'm getting some trouble making the threads share the iterator. I am not still used to the borrowing system: extern crate libc; extern crate num_cpus; use libc::{c_char, size_t}; use std::thread; use std::fs::copy; fn python_str_array_2_str_vec<T, U, V>(_: T, _: U) -> V { unimplemented!() } #[no_mangle] pub extern "C" fn copyFiles( sources: *const *const c_char, destinies: