rust

Error: closure requires unique access to `self` but `self` is already borrowed

荒凉一梦 提交于 2020-06-27 09:14:25
问题 I'm learning Rust, and have decided to implement a piece table (described in section 6.4 of this pdf) since it's fairly simple, but non-trivial. It's mostly been pretty straightforward, but I've run into one issue I'm not really able to figure out. Here's a simplified version of my code, for reference: use std::ops::Index; #[derive(Debug)] pub struct PieceTable { // original file data: never changes orig_buffer: Vec<u8>, // all new data is pushed onto this buffer add_buffer: Vec<u8>, // the

What's the idiomatic way to handle multiple `Option<T>` in Rust?

不想你离开。 提交于 2020-06-27 07:39:09
问题 Since I'm fairly new to Rust, I need guidance on how error handling is done idiomatically. I find the error-handling boilerplate really annoying. I'm stuck with multiple Option<T> s. It's too verbose to handle each None case manually. In Haskell, for example, you can chain optional value ( Maybe ) operations with a variety of operators: fmap , <*> , >>= , etc.: f x = x * x g x = x ++ x main = print $ g <$> show <$> f <$> Just 2 The same looks impossible in Rust. I'm trying to parse a two

How to create a tuple from a vector?

不羁的心 提交于 2020-06-27 07:13:33
问题 Here's an example that splits a string and parses each item, putting it into a tuple whose size is known at compile time. use std::str::FromStr; fn main() { let some_str = "123,321,312"; let num_pair_str = some_str.split(',').collect::<Vec<&str>>(); if num_pair_str.len() == 3 { let num_pair: (i32, i32, i32) = ( i32::from_str(num_pair_str[0]).expect("failed to parse number"), i32::from_str(num_pair_str[1]).expect("failed to parse number"), i32::from_str(num_pair_str[2]).expect("failed to parse

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?

耗尽温柔 提交于 2020-06-26 06:02:38
问题 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 tried to use immutable borrow but both did not work. fn main() { let mut vec1 = vec![4, 5]; vec1.push(6); for i in vec1 { if i % 2 == 0 { vec1.push(7); } } vec1.push(8); println!("vec1={:?}", vec1); } I expect to compile and change the vector inside and after the for loop. But it shows this error

How to avoid hard-coded values in Rust

Deadly 提交于 2020-06-26 04:48:09
问题 Below is a Maven/Java directory structure. - src - main - java - resources - test - java - resources - target Here, the resources folder holds application-related configuration files and resource files, to avoid hard-coding their contents in source files. How can I achieve the same in Rust with Cargo? 回答1: Maven doesn't include everything from your source. In fact, it includes the binary but doesn't even have to include the source at all in a .jar . You can configure it to say what to include

How to install a Rust target for a specific rustup toolchain?

廉价感情. 提交于 2020-06-25 15:54:14
问题 I am using rustc and cargo on my 64-bit Windows machine to compile a 32-bit application. This work fine when using the stable toolchain, but when I try to use the beta toolchain it fails. The beta toolchain was successfully installed with rustup install beta . In the project folder there is a .cargo/config file containing the following lines: [build] target = "i686-pc-windows-msvc" [target.i686-pc-windows-msvc] rustflags = ["-Ctarget-feature=+crt-static"] When running cargo +beta build the

How to return a vector of structs from Rust to C#?

▼魔方 西西 提交于 2020-06-24 21:29:07
问题 How is it possible to write Rust code like the C code below? This is my Rust code so far, without the option to marshal it: pub struct PackChar { id: u32, val_str: String, } #[no_mangle] pub extern "C" fn get_packs_char(size: u32) -> Vec<PackChar> { let mut out_vec = Vec::new(); for i in 0..size { let int_0 = '0' as u32; let last_char_val = int_0 + i % (126 - int_0); let last_char = char::from_u32(last_char_val).unwrap(); let buffer = format!("abcdefgHi{}", last_char); let pack_char =

How can one detect the OS type using Rust?

烂漫一生 提交于 2020-06-24 08:26:52
问题 How can one detect the OS type using Rust? I need to specify a default path specific to the OS. Should one use conditional compilation? For example: #[cfg(target_os = "macos")] static DEFAULT_PATH: &str = "path2"; #[cfg(target_os = "linux")] static DEFAULT_PATH: &str = "path0"; #[cfg(target_os = "windows")] static DEFAULT_PATH: &str = "path1"; 回答1: You can also use cfg! syntax extension. if cfg!(windows) { println!("this is windows"); } else if cfg!(unix) { println!("this is unix alike"); }

Why does Rust not have a return value in the main function, and how to return a value anyway?

谁都会走 提交于 2020-06-24 05:44:08
问题 In Rust the main function is defined like this: fn main() { } This function does not allow for a return value though. Why would a language not allow for a return value and is there a way to return something anyway? Would I be able to safely use the C exit(int) function, or will this cause leaks and whatnot? 回答1: As of Rust 1.26, main can return a Result : use std::fs::File; fn main() -> Result<(), std::io::Error> { let f = File::open("bar.txt")?; Ok(()) } The returned error code in this case

What can be done with Rust's generic FromStr object?

为君一笑 提交于 2020-06-23 12:55:42
问题 Rust's str class has a parse method that returns a FromStr object. parse is templated, and so the type that's being parsed from the str can be manually specified, e.g. "3".parse::<i32>() evaluates to (a Result object containing) the 32-bit int 3 . But failing to specify the type does not seem to be an error in itself. Instead, I get an error when trying to print the resulting (generic/unspecified) FromStr object: let foo = "3".parse(); match foo { Ok(m) => println!("foo: {}", m), Err(e) =>