Evaluations/Simplify Prompts
main
filtered_data.jsonl
texttext
DeepSeekDeepSeek/Deepseek V3
Fireworks AI Fireworks AI
prompt
Simplify the following title and body into a single question that encapsulates everything the user is asking. Strip out all the html, the question should be in plain text and contain all the context necessary. If there is any sample code or error messages, make sure to include them. Keep the necessary code for the question if provided.

Title:
{title}

Body:
{body}

Simplified Question and Code:
Feb 2, 2025, 4:18 AM UTC
Feb 2, 2025, 7:44 AM UTC
03:25:53
1514 rows
1262012 tokens$ 1.14
1514 rows processed, 1262012 tokens used ($1.14)
completed
4 columns, 1-100 of 1514 rows
title
body
How can I generate a random number within a range in Rust?
<blockquote> <p>Editor's note: This code example is from a version of Rust prior to 1.0 and is not syntactically valid Rust 1.0 code. Updated versions of this code produce different errors, but the answers still contain valuable information.</p> </blockquote> <p>I came across the following example of how to generate a random number using Rust, but it doesn't appear to work. The example doesn't show which version of Rust it applies to, so perhaps it is out-of-date, or perhaps I got something wrong.</p> <pre><code>// http://static.rust-lang.org/doc/master/std/rand/trait.Rng.html use std::rand; use std::rand::Rng; fn main() { let mut rng = rand::task_rng(); let n: uint = rng.gen_range(0u, 10); println!("{}", n); let m: float = rng.gen_range(-40.0, 1.3e5); println!("{}", m); } </code></pre> <p>When I attempt to compile this, the following error results:</p> <pre class="lang-none prettyprint-override"><code>test_rand002.rs:6:17: 6:39 error: type `@mut std::rand::IsaacRng` does not implement any method in scope named `gen_range` test_rand002.rs:6 let n: uint = rng.gen_range(0u, 10); ^~~~~~~~~~~~~~~~~~~~~~ test_rand002.rs:8:18: 8:46 error: type `@mut std::rand::IsaacRng` does not implement any method in scope named `gen_range` test_rand002.rs:8 let m: float = rng.gen_range(-40.0, 1.3e5); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ </code></pre> <p>There is another example (as follows) on the same page (above) that does work. However, it doesn't do exactly what I want, although I could adapt it.</p> <pre><code>use std::rand; use std::rand::Rng; fn main() { let mut rng = rand::task_rng(); let x: uint = rng.gen(); println!("{}", x); println!("{:?}", rng.gen::&lt;(f64, bool)&gt;()); } </code></pre> <p>How can I generate a "simple" random number using Rust (e.g.: <code>i64</code>) within a given range (e.g.: 0 to n)?</p>
Compilation error: can't find crate for `core`
<p>I'm using Rust 1.35.0 to try out some Rust examples and I could not get it to compile, as I keep getting the following message:</p> <pre class="lang-none prettyprint-override"><code>error[E0463]: can't find crate for `core` </code></pre> <p>I ran <code>rustc --explain E0463</code> and I see the following message:</p> <pre class="lang-none prettyprint-override"><code>You need to link your code to the relevant crate in order to be able to use it (through Cargo or the `-L` option of rustc example). Plugins are crates as well, and you link to them the same way. </code></pre> <p>Here is my Cargo.toml:</p> <pre><code>[package] name = "sensor-node" version = "0.1.0" authors = ["joesan &lt;email@gmail.com&gt;"] edition = "2018" [dependencies] dwm1001 = "0.1.0" panic-halt = "0.2.0" nb = "0.1.1" </code></pre> <p>Here is my main.rs:</p> <pre><code>fn main() { let s = String::from("hello"); // s comes into scope takes_ownership(s); // s's value moves into the function... // ... and so is no longer valid here let x = 5; // x comes into scope makes_copy(x); // x would move into the function, // but i32 is Copy, so it’s okay to still // use x afterward } // Here, x goes out of scope, then s. But because s's value was moved, nothing // special happens. fn takes_ownership(some_string: String) { // some_string comes into scope println!("{}", some_string); } // Here, some_string goes out of scope and `drop` is called. The backing // memory is freed. fn makes_copy(some_integer: i32) { // some_integer comes into scope println!("{}", some_integer); } // Here, some_integer goes out of scope. Nothing special happens. </code></pre>
Is there a list of all cfg features?
<p>Rust has the ability to <a href="https://doc.rust-lang.org/book/conditional-compilation.html" rel="noreferrer">check configuration at build</a> time with, e.g., <code>#[cfg(target_os = "linux")]</code> or <code>if cfg!(target_os = "linux") {...}</code>, where <code>target_os</code> is a <em>feature</em>.</p> <p>Is there a list of all (or, at least, commonly used) features that can be checked in Rust?</p> <hr> <p>See related question regarding <em>attributes</em> <a href="https://stackoverflow.com/questions/37900513/is-there-an-exhaustive-list-of-standard-attributes-anywhere?noredirect=1&amp;lq=1">Is there an exhaustive list of standard attributes anywhere?</a>.</p>
How to include files from same directory in a module using Cargo/Rust?
<p>I have a Cargo project consisting of three files in the same directory: <code>main.rs</code>, <code>mod1.rs</code> and <code>mod2.rs</code>. </p> <p>I want to import functions from <code>mod2.rs</code> to <code>mod1.rs</code> the same way I would import functions from <code>mod1.rs</code> to <code>main.rs</code>.<br> I've read about the file structure required but I don't get it - naming all the imported files <code>mod</code> will lead to minor confusion in the editor and also this just complicates the project hierarchy. </p> <p>Is there a way to import/include files independently of directory structure as I would in Python or C++? </p> <p>main.rs:</p> <pre><code>mod mod1; // Works fn main() { println!("Hello, world!"); mod1::mod1fn(); } </code></pre> <p>mod1.rs:</p> <pre><code>mod mod2; // Fails pub fn mod1fn() { println!("1"); mod2::mod2fn(); } </code></pre> <p>mod2.rs:</p> <pre><code>pub fn mod2fn() { println!("2"); } </code></pre> <p>Building results in:</p> <pre class="lang-none prettyprint-override"><code>error: cannot declare a new module at this location --&gt; src\mod1.rs:1:5 | 1 | mod mod2; | ^^^^ | note: maybe move this module `src` to its own directory via `src/mod.rs` --&gt; src\mod1.rs:1:5 | 1 | mod mod2; | ^^^^ note: ... or maybe `use` the module `mod2` instead of possibly redeclaring it --&gt; src\mod1.rs:1:5 | 1 | mod mod2; | ^^^^ </code></pre> <p>I can't <code>use</code> it as it doesn't exist as a module anywhere, and I don't want to modify the directory structure.</p>
What is the difference between traits in Rust and typeclasses in Haskell?
<p><a href="https://doc.rust-lang.org/rust-by-example/trait.html" rel="noreferrer">Traits</a> in Rust seem at least superficially similar to <a href="http://en.wikipedia.org/wiki/Type_class" rel="noreferrer">typeclasses</a> in Haskell, however I've seen people write that there are some differences between them. I was wondering exactly what these differences are.</p>
Right way to have Function pointers in struct
<p>I'm trying to make a struct that has a mutable function pointer. I have it setup so that the function pointer is initialized to a particular function, but rust doesn't recognize the pointer when i try to use it. </p> <p>i get </p> <pre><code>hello.rs:24:14: 24:22 error: no method named `get_func` found for type `&amp;Container` in the current scope hello.rs:24 self.get_func(self, key) ^~~~~~~~ </code></pre> <p>here's my code</p> <pre><code>use std::collections::HashMap; struct Container { field: HashMap&lt;String, i32&gt;, get_func: fn(&amp;Container, &amp;str) -&gt; i32 } fn regular_get(obj: &amp;Container, key: &amp;str) -&gt; i32 { obj.field[key] } impl Container { fn new(val: HashMap&lt;String, i32&gt;) -&gt; Container { Container { field: val, get_func: regular_get } } fn get(&amp;self, key: &amp;str) -&gt; i32 { self.get_func(self, key) } } fn main() { let mut c:HashMap&lt;String, i32&gt; = HashMap::new(); c.insert("dog".to_string(), 123); let s = Container::new(c); println!("{} {}", 123, s.get("dog")); } </code></pre>
Is there a way to get the field names of a struct in a macro?
<p>Consider the following example:</p> <pre><code>struct S { a: String, b: String, } </code></pre> <p>I have a macro which is called like this:</p> <pre><code>my_macro!(S); </code></pre> <p>I want to access the field names of the struct in the macro like this:</p> <pre><code>macro_rules! my_macro { ($t:ty) =&gt; {{ let field_names = get_field_names($t); // do something with field_names }}; } </code></pre> <p>I'm new to Rust and macros, so maybe I'm missing something obvious.</p>
Why is type conversion from u64 to usize allowed using `as` but not `From`?
<p>The first conversion using 'as' compiles, but the second one using the 'From' trait does not:</p> <pre><code>fn main() { let a: u64 = 5; let b = a as usize; let b = usize::from(a); } </code></pre> <p>Using Rust 1.34.0, I get the following error:</p> <pre class="lang-none prettyprint-override"><code>error[E0277]: the trait bound `usize: std::convert::From&lt;u64&gt;` is not satisfied --&gt; src/main.rs:4:13 | 4 | let b = usize::from(a); | ^^^^^^^^^^^ the trait `std::convert::From&lt;u64&gt;` is not implemented for `usize` | = help: the following implementations were found: &lt;usize as std::convert::From&lt;bool&gt;&gt; &lt;usize as std::convert::From&lt;std::num::NonZeroUsize&gt;&gt; &lt;usize as std::convert::From&lt;u16&gt;&gt; &lt;usize as std::convert::From&lt;u8&gt;&gt; = note: required by `std::convert::From::from` </code></pre> <p>When I replace <code>u64</code> with <code>u8</code>, there is no more error. From the error message, I understand that the <code>From</code> trait is implemented only for <code>u8</code>, but not for the other integer types.</p> <p>If there is a good reason for that, then why shouldn't the conversion using 'as' should also fail to compile?</p>
How do I debug macros?
<p>So I've got the following macro code I'm trying to debug. I've taken it from the <a href="http://doc.rust-lang.org/book/macros.html" rel="noreferrer" title="The Rust Programming Language Book">Rust Book</a> under the section "The deep end". I renamed the variables within the macro to more closely follow <a href="http://esolangs.org/wiki/Bitwise_Cyclic_Tag" rel="noreferrer" title="Bitwise Cyclic Tag">this</a> post.</p> <p>My goal is to have the program print out each line of the BCT program. I'm well aware that this is very compiler heavy.</p> <p>The only error rustc is giving me is:</p> <pre><code>user@debian:~/rust/macros$ rustc --pretty expanded src/main.rs -Z unstable-options &gt; src/main.precomp.rs src/main.rs:151:34: 151:35 error: no rules expected the token `0` src/main.rs:151 bct!(0, 1, 1, 1, 0, 0, 0; 1, 0); </code></pre> <p>What steps can I take to figure out <strong><em>where</em></strong> in the macro the problem is coming from?</p> <p>Here's my code:</p> <pre><code>fn main() { { // "Bitwise Cyclic Tag" automation through macros macro_rules! bct { // cmd 0: 0 ... =&gt; ... (0, $($program:tt),* ; $_head:tt) =&gt; (bct_p!($($program),*, 0 ; )); (0, $($program:tt),* ; $_head:tt, $($tail:tt),*) =&gt; (bct_p!($($program),*, 0 ; $($tail),*)); // cmd 1x: 1 ... =&gt; 1 ... x (1, $x:tt, $($program:tt),* ; 1) =&gt; (bct_p!($($program),*, 1, $x ; 1, $x)); (1, $x:tt, $($program:tt),* ; 1, $($tail:tt),*) =&gt; (bct_p!($($program),*, 1, $x ; 1, $($tail),*, $x)); // cmd 1x: 0 ... =&gt; 0 ... (1, $x:tt, $($program:tt),* ; $($tail:tt),*) =&gt; (bct_p!($($program),*, 1, $x ; $($tail),*)); // halt on empty data string ( $($program:tt),* ; ) =&gt; (()); } macro_rules! print_bct { ($x:tt ; ) =&gt; (print!("{}", stringify!($x))); ( ; $d:tt) =&gt; (print!("{}", stringify!($d))); ($x:tt, $($program:tt),* ; ) =&gt; { print!("{}", stringify!($x)); print_bct!($program ;); }; ($x:tt, $($program:tt),* ; $($data:tt),*) =&gt; { print!("{}", stringify!($x)); print_bct!($program ; $data); }; ( ; $d:tt, $($data:tt),*) =&gt; { print!("{}", stringify!($d)); print_bct!( ; $data); }; } macro_rules! bct_p { ($($program:tt),* ; ) =&gt; { print_bct!($($program:tt),* ; ); println!(""); bct!($($program),* ; ); }; ($($program:tt),* ; $(data:tt),*) =&gt; { print_bct!($($program),* ; $($data),*); println!(""); bct!($($program),* ; $($data),*); }; } // the compiler is going to hate me... bct!(0, 1, 1, 1, 0, 0, 0; 1, 0); } </code></pre>
Dividing two integers doesn't print as a decimal number in Rust
<p>I'm learning Rust, but when I print a decimal number, only the integer part is printed, not the decimal part:</p> <pre><code>fn main(){ println!("{:.3}", 22/7); } // This only show 3 </code></pre> <p>but when I print the decimal number explicitly, it works correctly:</p> <pre><code>fn main(){ println!("{:.3}", 0.25648); } // this print 0.256 </code></pre>
How do you make a GET request in Rust?
<p>I noticed that Rust doesn't have a builtin library to deal with HTTP, it only has a <code>net</code> module that deals with raw IP and TCP protocols.</p> <p>I need to take a <code>&amp;str</code> of the URL, make a HTTP GET request, and if successful return either a <code>String</code> or <code>&amp;str</code> that corresponds to the HTML or JSON or other response in string form.</p> <p>It would look something like:</p> <pre><code>use somelib::http; let response = http::get(&amp;"http://stackoverflow.com"); match response { Some(suc) =&gt; suc, None =&gt; panic! } </code></pre>
Are nested matches a bad practice in idiomatic Rust?
<p>I have a <code>get_url_content</code> function and don't care about errors (it's just a test). It returns an <code>Option&lt;String&gt;</code>.</p> <pre><code>extern crate hyper; use std::io::Read; use hyper::client::Client; fn get_url_content(url: &amp;str) -&gt; Option&lt;String&gt; { let client = Client::new(); let mut s = String::new(); match client.get(url).send() { Ok(mut res) =&gt; { match res.read_to_string(&amp;mut s) { Ok(_) =&gt; { Some(s) }, Err(_) =&gt; { None } } }, Err(_) =&gt; { None } } } </code></pre> <p>This function works fine but I find it's not easy to read. I think there are some best practices about this kind of case to make it more readable. Are nested matches a bad practice (like callback hell in JS) and if so, how to avoid it?</p>
How do I pass an array to a function in Rust and change its content?
<p>I want to pass an array to a function and change the content inside it:</p> <pre class="lang-rust prettyprint-override"><code>fn change_value(mut arr: &amp;[i32]) { arr[1] = 10; } fn main() { let mut arr: [i32; 4] = [1, 2, 3, 4]; change_value(&amp;arr); println!(&quot;this is {}&quot;, arr[1]); } </code></pre> <p>I'm getting this error:</p> <pre class="lang-none prettyprint-override"><code>warning: variable does not need to be mutable --&gt; src/main.rs:2:17 | 2 | fn change_value(mut arr: &amp;[i32]) { | ----^^^ | | | help: remove this `mut` | = note: `#[warn(unused_mut)]` on by default error[E0594]: cannot assign to `arr[_]` which is behind a `&amp;` reference --&gt; src/main.rs:3:5 | 2 | fn change_value(mut arr: &amp;[i32]) { | ------ help: consider changing this to be a mutable reference: `&amp;mut [i32]` 3 | arr[1] = 10; | ^^^^^^^^^^^ `arr` is a `&amp;` reference, so the data it refers to cannot be written warning: variable does not need to be mutable --&gt; src/main.rs:7:9 | 7 | let mut arr: [i32; 4] = [1, 2, 3, 4]; | ----^^^ | | | help: remove this `mut` </code></pre> <p>I've been searching around, but I can't find anything.</p>
How to wrap a raw string literal without inserting newlines into the raw string?
<p>I have a raw string literal which is very long. Is it possible to split this across multiple lines without adding newline characters to the string?</p> <pre><code>file.write(r#"This is an example of a line which is well over 100 characters in length. Id like to know if its possible to wrap it! Now some characters to justify using a raw string \foo\bar\baz :)"#) </code></pre> <p>In Python and C for example, you can simply write this as multiple string literals.</p> <pre><code># "some string" (r"some " r"string") </code></pre> <p>Is it possible to do something similar in Rust?</p>
Rust diesel orm queries
<p>I am new to rust and diesel orm. I am trying to execute below things on my query:</p> <ul> <li>count</li> <li>select</li> <li>order</li> <li>limit</li> </ul> <p>but I am getting error.<br> I am using postgres database.<br></p> <p>I have added the exact error above the queries in comment.<br> Here are my code:</p> <p><strong>schema.rs</strong></p> <pre><code>table! { employee (employee_id) { employee_id -&gt; Int4, name -&gt; Nullable&lt;Text&gt;, age -&gt; Nullable&lt;Int4&gt;, address -&gt; Nullable&lt;Text&gt;, email -&gt; Nullable&lt;Text&gt;, dept_id -&gt; Int4, salary -&gt; Nullable&lt;Numeric&gt;, created_on -&gt; Nullable&lt;Timestamp&gt;, created_by -&gt; Nullable&lt;Text&gt;, modified_on -&gt; Nullable&lt;Timestamp&gt;, modified_by -&gt; Nullable&lt;Text&gt;, is_active -&gt; Nullable&lt;Bool&gt;, } } </code></pre> <p><strong>models.rs</strong></p> <pre><code>#![allow(unused)] #![allow(clippy::all)] use super::schema::employee; use bigdecimal::BigDecimal; use chrono::NaiveDateTime; #[derive(Queryable, Debug, Identifiable)] #[table_name = &quot;employee&quot;] #[primary_key(employee_id)] pub struct Employee { pub employee_id: i32, pub name: Option&lt;String&gt;, pub age: Option&lt;i32&gt;, pub address: Option&lt;String&gt;, pub email: Option&lt;String&gt;, pub dept_id: i32, pub salary: Option&lt;BigDecimal&gt;, pub created_on: Option&lt;NaiveDateTime&gt;, pub created_by: Option&lt;String&gt;, pub modified_on: Option&lt;NaiveDateTime&gt;, pub modified_by: Option&lt;String&gt;, pub is_active: Option&lt;bool&gt;, } </code></pre> <p><strong>cargo.toml</strong></p> <pre><code>[dependencies] diesel = { version = &quot;1.4.5&quot;, features = [&quot;postgres&quot;,&quot;chrono&quot;,&quot;numeric&quot;] } dotenv = &quot;0.15.0&quot; chrono = { version = &quot;0.4.19&quot; , features = [&quot;serde&quot;] } bigdecimal = { version = &quot;0.1.0&quot; } </code></pre> <p><strong>main.rs</strong></p> <pre><code>#[macro_use] extern crate diesel; extern crate bigdecimal; extern crate chrono; extern crate dotenv; use crate::models::Employee; use crate::models::Players; use crate::schema::employee::dsl::*; use diesel::{pg::PgConnection, prelude::*}; use dotenv::dotenv; use std::env; mod models; mod schema; fn main() { dotenv().ok(); let data_url: String = env::var(&quot;DATABASE_URL&quot;).expect(&quot;DATABASE_URL must be set&quot;); let connection: PgConnection = PgConnection::establish(&amp;data_url).expect(&amp;format!(&quot;Error connect to {}&quot;, data_url)); //get all employees name //This is working fine let _employee: Vec&lt;Employee&gt; = employee .load::&lt;Employee&gt;(&amp;connection) .expect(&quot;Error loading department&quot;); for emp in _employee { println!(&quot;{}&quot;, emp.name.unwrap_or_default()); } //---------------------------------------------- //get employees count /* Error: error[E0282]: type annotations needed ^^^^^^^^^^^^^^^ consider giving `total_employees` a type */ let total_employees = employee.count().get_result(&amp;connection).expect(&quot;Error&quot;); println!(&quot;{}&quot;, total_employees); //----------------------------------------------- //get all names /* Error: error[E0277]: the trait bound `*const str: FromSql&lt;diesel::sql_types::Nullable&lt;diesel::sql_types::Text&gt;, _&gt;` is not satisfied ^^^^ the trait `FromSql&lt;diesel::sql_types::Nullable&lt;diesel::sql_types::Text&gt;, _&gt;` is not implemented for `*const str` */ let all_names = employee.select(name).load::&lt;String&gt;(&amp;connection)?; println!(&quot;{}&quot;, all_names); //---------------------------------------------- //order name /* Error: error[E0277]: the trait bound `*const str: FromSql&lt;diesel::sql_types::Nullable&lt;diesel::sql_types::Text&gt;, _&gt;` is not satisfied ^^^^ the trait `FromSql&lt;diesel::sql_types::Nullable&lt;diesel::sql_types::Text&gt;, _&gt;` is not implemented for `*const str` */ let ordered_names = employee .select(name) .order(name.desc()) .load::&lt;String&gt;(&amp;connection)?; println!(&quot;{}&quot;, ordered_names); //------------------------------------------------ /* Error: error[E0277]: the trait bound `*const str: FromSql&lt;diesel::sql_types::Nullable&lt;diesel::sql_types::Text&gt;, _&gt;` is not satisfied ^^^^ the trait `FromSql&lt;diesel::sql_types::Nullable&lt;diesel::sql_types::Text&gt;, _&gt;` is not implemented for `*const str` */ let limited = employee .select(name) .order(employee_id) .limit(1) .load::&lt;String&gt;(&amp;connection)?; println!(&quot;{}&quot;, limited); } </code></pre> <p>Am I missing something ? Can anybody correct me ? <br> Thanks!</p>
How to create a function returning a borrowed value?
<p>I have the following function as part of a Rust WASM application to convert a <code>Box</code>ed closure into the Rust-representation for a JavaScript function.</p> <pre><code>use js_sys::Function; type Callback = Rc&lt;RefCell&lt;Option&lt;Closure&lt;FnMut()&gt;&gt;&gt;&gt;; fn to_function(callback: &amp;Callback) -&gt; &amp;Function { callback.borrow().as_ref().unwrap().as_ref().unchecked_ref() } </code></pre> <p>However, the compiler complains that the return value uses a borrowed value (obtained with <code>callback.borrow()</code>) so cannot be returned.</p> <p>Hence, I decided to add lifetime annotations to inform the compiler that this new reference should live as long as the input.</p> <pre><code>use js_sys::Function; type Callback = Rc&lt;RefCell&lt;Option&lt;Closure&lt;FnMut()&gt;&gt;&gt;&gt;; fn to_function&lt;'a&gt;(callback: &amp;'a Callback) -&gt; &amp;'a Function { callback.borrow().as_ref().unwrap().as_ref().unchecked_ref() } </code></pre> <p>Unfortunately, this hasn't helped and I get the same error. What am I doing wrong here?</p>
How to wrap a call to a FFI function that uses VarArgs in Rust?
<p><code>mexPrintf</code>, just like <code>printf</code>, accepts a varargs list of arguments, but I don't know what the best way to wrap this is in Rust. There is a <a href="https://github.com/rust-lang/rfcs/issues/376" rel="nofollow noreferrer">RFC for variadic generics</a>, but what can we do today?</p> <p>In this example, I want to print of the number of inputs and outputs, but the wrapped function just prints garbage. Any idea how to fix this?</p> <p><a href="https://i.stack.imgur.com/5SRYq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5SRYq.png" alt="enter image description here"></a></p> <pre><code>#![allow(non_snake_case)] #![allow(unused_variables)] extern crate mex_sys; use mex_sys::mxArray; use std::ffi::CString; use std::os::raw::c_int; use std::os::raw::c_void; type VarArgs = *mut c_void; // attempt to wrap mex_sys::mexPrintf fn mexPrintf(fmt: &amp;str, args: VarArgs) { let cs = CString::new(fmt).unwrap(); unsafe { mex_sys::mexPrintf(cs.as_ptr(), args); } } #[no_mangle] pub extern "system" fn mexFunction( nlhs: c_int, plhs: *mut *mut mxArray, nrhs: c_int, prhs: *mut *mut mxArray, ) { let hw = CString::new("hello world\n").unwrap(); unsafe { mex_sys::mexPrintf(hw.as_ptr()); } let inout = CString::new("%d inputs and %d outputs\n").unwrap(); unsafe { mex_sys::mexPrintf(inout.as_ptr(), nrhs, nlhs); } mexPrintf("hello world wrapped\n", std::ptr::null_mut()); let n = Box::new(nrhs); let p = Box::into_raw(n); mexPrintf("inputs %d\n", p as VarArgs); let mut v = vec![3]; mexPrintf("vec %d\n", v.as_mut_ptr() as VarArgs); } </code></pre>
How to store JoinHandle of a thread to close it later
<p>I am trying to run a thread in background and then change an AtomicBool to ask the thread to stop. To ensure the thread stopped properly, I want to call <code>join</code> method of the JoinHandle.</p> <p>Instead of calling join, if I just wait (<code>thread::sleep_ms</code>) for sometime after setting the AtomicBool, the thread properly closes. But to ensure this I want to use join. Or is there any better method to ensure the thread closed properly?</p> <pre class="lang-rust prettyprint-override"><code>use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; use std::thread; use std::thread::JoinHandle; struct MyInner { s: String } struct My { inner: Arc&lt;Mutex&lt;MyInner&gt;&gt;, close_thread: Arc&lt;AtomicBool&gt;, my_thread: JoinHandle&lt;()&gt; } impl MyInner { fn new(s: String) -&gt; MyInner { MyInner { s: s } } } impl My { fn new(s: String) -&gt; My { My { inner: Arc::new(Mutex::new(MyInner::new(s))), close_thread: Arc::new(AtomicBool::new(false)), my_thread: thread::spawn(move || {}) } } fn stop_thread(&amp;self) { self.close_thread.swap(true, Ordering::Relaxed); // ERROR! self.my_thread.join().expect("Couldn't join my_thread on the main thread"); } fn start(&amp;mut self) { let local_self = self.inner.clone(); let close_thread = self.close_thread.clone(); self.my_thread = thread::spawn(move || { loop { if close_thread.load(Ordering::Relaxed) { println!("Closing thread!"); return; } let gaurd = local_self.lock().unwrap(); println!("Local self has value: {}", (*gaurd).s); std::mem::drop(gaurd); thread::sleep_ms(1000); } }); } } fn main() { let mut m = My::new("blo".to_owned()); m.start(); thread::sleep_ms(2000); m.stop_thread(); println!("Complete!"); } </code></pre> <p>For the above code, I get the error:</p> <pre class="lang-none prettyprint-override"><code>error[E0507]: cannot move out of `self.my_thread` which is behind a shared reference --&gt; src/main.rs:35:9 | 35 | self.my_thread.join().expect("Couldn't join my_thread on the main thread"); | ^^^^^^^^^^^^^^ move occurs because `self.my_thread` has type `std::thread::JoinHandle&lt;()&gt;`, which does not implement the `Copy` trait </code></pre> <p>I also tried using <code>Arc</code> on the JoinHandle but even after <code>Arc::clone</code> I get the same error.</p>
Rust constants in different modules?
<p>I have this "main.rs" file which I declare a version constant. </p> <pre><code>pub const VERSION: &amp;'static str = "v2"; mod game; fn main() { do_stuff(); } </code></pre> <p>Then I want to access this global constant in a different module "game.rs":</p> <pre><code>pub fn do_stuff() { println!("This is version: {}", VERSION); } </code></pre> <p>How do I make the constant available everywhere?</p>
How do I return a &Path from a function?
<p>I'm trying to understand how to write proper Rust code, but I think I may be overestimating the power of the compiler's ability to understand the lifetimes of my objects. This is the code as I expected it to work:</p> <pre><code>use std::path::Path; use std::env; use rusqlite::SqliteConnection; struct SomeDatabase { conn: SqliteConnection, } impl SomeDatabase { fn getPath() -&gt; &amp;Path { let path = env::home_dir().unwrap(); path.push("foo.sqlite3"); path.as_path() } fn open() -&gt; SomeDatabase { let path = SomeDatabase::getPath() SomeDatabase { conn: SqliteConnection::open(path).unwrap() } } } fn main() { let db = SomeDatabase::open(); } </code></pre> <p>When I try to compile this, I get an error about a missing lifetime specifier on <code>&amp;Path</code>. I know if this took a reference parameter from the caller, it would take on the same lifetime as that reference has. Here though what I was expecting is that the lifetime would be attached to the variable I am assigning the result to.</p> <p>I know lifetimes can be added explicitly, but I don't know how to apply them in this case. The compiler suggests trying the <code>'static</code> lifetime, but that doesn't make sense here as far as I know because the source of this function's return value isn't static.</p> <p>Now, just to try to see what happened if I tried to compile the rest of the code, I changed the return type from <code>&amp;Path</code> to <code>PathBuf</code> and called <code>as_path()</code> in <code>open()</code>. This caused the compiler to output these errors:</p> <pre><code>src\main.rs:22:30: 22:52 error: the trait `core::marker::Sized` is not implemented for the type `[u8]` [E0277] src\main.rs:22 SomeDatabase { conn: SqliteConnection::open(path).unwrap() } ^~~~~~~~~~~~~~~~~~~~~~ src\main.rs:22:30: 22:52 note: `[u8]` does not have a constant size known at compile-time src\main.rs:22 SomeDatabase { conn: SqliteConnection::open(path).unwrap() } ^~~~~~~~~~~~~~~~~~~~~~ </code></pre> <p><code>SqliteConnection::open()</code> returns a <code>Result&lt;SqliteConnection, SqliteError&gt;</code> and the only field inside <code>SqliteConnection</code> is a <code>RefCell</code>, so I don't understand where this error about a byte array is coming from.</p> <p>So, why aren't things working as I expect and what is the most Rusty way to write this code? </p>
Can macros match against constant arguments instead of literals?
<p>Given the <a href="https://doc.rust-lang.org/book/macros.html#matching" rel="nofollow">macro matching example</a>, this shows how macros can match an argument.</p> <p>I've made very minor changes here to use numbers:</p> <pre><code>macro_rules! foo { (0 =&gt; $e:expr) =&gt; (println!("mode X: {}", $e)); (1 =&gt; $e:expr) =&gt; (println!("mode Y: {}", $e)); } fn main() { foo!(1 =&gt; 3); } </code></pre> <p>Works, printing: <code>mode Y: 3</code></p> <p>However I would like to use a constant as an argument, can this be made to work:</p> <pre><code>const CONST: usize = 1; macro_rules! foo { (0 =&gt; $e:expr) =&gt; (println!("mode X: {}", $e)); (1 =&gt; $e:expr) =&gt; (println!("mode Y: {}", $e)); } fn main() { foo!(CONST =&gt; 3); } </code></pre> <p>Is this possible in Rust?</p> <hr> <p>Note, using a regular <code>match</code> statement isn't usable for me, since in my code each branch resolves to different types, giving an error. So I'm specifically interested to know if a constant can be passed to a macro.</p>
How can I include private modules when generating documentation via Cargo?
<p>I'm currently working on a project with Rust and Cargo. It works well, but I encounter a little issue: for code reuse, most of my project is inside a lib crate. In this crate, a lot of things is private. So when I do <code>cargo doc</code>, I just have documentation for public, exported stuff... which is actually great, because it's easy to see what is exported and what is not.</p> <p>But I have to admit: I miss a complete documentation of the whole project, for development purpose...</p>
DirectoryNotFoundException - Could Not Find Part of the Path
<p>I have a console application I built for myself to rename <code>.mp3</code> files I download. This application has worked flawlessly for quite a few months, but is all of a sudden tossing the titled exception at me with one particular directory. Not only is it this one directory, but is happening on only a select number of files - 3 of them were successfully renamed.</p> <p>Here is my directory path and files:</p> <p><a href="https://i.stack.imgur.com/OTcsf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OTcsf.png" alt="enter image description here"></a></p> <p>Here is a snippet of the directory path where the exception is thrown, along with the exception's message:</p> <p><a href="https://i.stack.imgur.com/qLDUA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qLDUA.png" alt="enter image description here"></a></p> <p>And here is my code:</p> <pre><code>static void Main(string[] args) { string dir = @"M:\Temp Downloading Folder"; var files = new DirectoryInfo(dir + @"\Gregory Alan Isakov Discography [2005 - 2013]\Rust Colored Stones").GetFiles("*.mp3").ToList(); foreach (var item in files) { if (item.Name.Substring(0, 2).All(char.IsDigit)) { //string fullName = item.FullName.Replace("\\", "/"); string newName = "Gregory Alan Isakov "; //exception thrown here File.Move(item.FullName, item.FullName.Replace(item.Name.Substring(0, 3), newName)); } } Console.WriteLine("Done!"); Console.ReadKey(); } </code></pre> <p>I tried changing the path to have <code>/</code> instead of <code>\\</code> with the same result.</p> <p>According to the <a href="https://msdn.microsoft.com/en-us/library/system.io.directorynotfoundexception(v=vs.110).aspx" rel="nofollow noreferrer">Documentation on MSDN</a>:</p> <blockquote> <p>The exception that is thrown when part of a file or directory cannot be found.</p> </blockquote> <p>However, the directory <em>is</em> found and correctly renamed the first 3 files (as depicted in the first image).</p> <p>Can anyone explain to me why this is happening?</p>
What does {:?} mean in a Rust format string?
<p>I found out that <code>{:?}</code> prints an entire array in Rust. I want to know what is it called and how exactly it works. Is it only limited to printing arrays or could it also be used elsewhere for other purposes?</p>
AngularJS orderby not working as expected
<p>I am using Angular directive to orderBy on table rows, with the data coming as an array of objects from a service.</p> <pre><code>&lt;tr ng-repeat="album in vm.albums | orderBy: album.data.title"&gt; &lt;td&gt;{{album.data.title}}&lt;/td&gt; &lt;td&gt;{{album.data.date}}&lt;/td&gt; &lt;td&gt;{{album.data.type}}&lt;/td&gt; &lt;td&gt;{{album.data.username}}&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Here's what my <code>vm.albums</code> array looks like:</p> <pre><code>vm.albums ---&gt; [&gt;Object1, &gt;Object2, &gt;Object3......] </code></pre> <p>And each object looks like the foll:</p> <pre><code>Object1 ---&gt; {slug: "my-title", data: Object} Object2 ---&gt; {slug: "beta-title", data: Object} Object3 ---&gt; {slug: "alpha-title", data: Object} </code></pre> <p>And the object <code>Object1.data</code> or any object in the vm.albums array looks like the following:</p> <pre><code>Object1.data ---&gt; {title: "My Title", date: "2015-04-06", type: "Blue", username: 'rust'} Object2.data ---&gt; {title: "Beta Title", date: "2012-04-07", type: "Orange", username: 'badname'} Object3.data ---&gt; {title: "Alpha Title", date: "2013-09-06", type: "Lemons", username: 'xerox'} </code></pre> <p>I still don't get the right sorted <code>&lt;td&gt;</code> in my table using the <code>orderBy</code> I am using. Not sure what I am doing wrong. Any clue ?</p>
Splitting a `Vec`
<p>I'm trying to write a little buffer-thing for parsing so I can pull records off the front of as I parse them out, ideally without making any copies and just transferring ownership of chunks of the front of the buffer off as I run. Here's my implementation:</p> <pre><code>struct BufferThing { buf: Vec&lt;u8&gt;, } impl BufferThing { fn extract(&amp;mut self, size: usize) -&gt; Vec&lt;u8&gt; { assert!(size &lt;= self.buf.len()); let remaining: usize = self.buf.len() - size; let ptr: *mut u8 = self.buf.as_mut_ptr(); unsafe { self.buf = Vec::from_raw_parts(ptr.offset(size as isize), remaining, remaining); Vec::from_raw_parts(ptr, size, size) } } } </code></pre> <p>This compiles, but panics with a <code>signal: 11, SIGSEGV: invalid memory reference</code> as it starts running. This is mostly the same code as the example in <a href="https://doc.rust-lang.org/nomicon/borrow-splitting.html" rel="noreferrer">the Nomicon</a>, but I'm trying to do it on <code>Vec</code>'s and I'm trying to split a field instead of the object itself.</p> <p>Is it possible to do this without copying out one of the <code>Vec</code>s? And is there some section of the Nomicon or other documentation that explains why I'm blowing everything up in the <code>unsafe</code> block?</p>
Why are const atomic variables not updated, but static atomic variables are?
<p>I have this code:</p> <pre><code>use std::sync::atomic::{AtomicUsize, Ordering}; const SOME_VAR: AtomicUsize = AtomicUsize::new(0); fn main() { println!("{}", SOME_VAR.load(Ordering::SeqCst)); println!("{}", SOME_VAR.fetch_add(10, Ordering::SeqCst)); println!("{}", SOME_VAR.load(Ordering::SeqCst)); } </code></pre> <p>This prints <code>0 0 0</code> without any errors. In Java, I can use a <code>final HashMap</code> and add <code>(k, v)</code> to it. In Rust, I am surprised that the compiler is not yelling at me but also does not increment my atomic value. Am I doing something wrong here?</p> <p>If I use a <code>static</code>: </p> <pre><code>static SOME_VAR: AtomicUsize = AtomicUsize::new(0); </code></pre> <p>I get the result <code>0 0 10</code>. Why does it not work with <code>const</code>?</p>
Why are len() and is_empty() not defined in a trait?
<p>Most patterns in Rust are captured by traits (<code>Iterator</code>, <code>From</code>, <code>Borrow</code>, etc.).</p> <p>How come a pattern as pervasive as <code>len</code>/<code>is_empty</code> has no associated trait in the standard library? Would that cause problems which I do not foresee? Was it deemed useless? Or is it only that nobody thought of it (which seems unlikely)? </p>
How to create *mut u8 from Rust string?
<p>I'm new to Rust. I want to create a mutable u8 buffer. </p> <p>I tried</p> <pre><code>let mut str = "hello"; let r = str as *mut u8; </code></pre> <p>but I get</p> <pre><code>error[E0606]: casting `&amp;str` as `*mut u8` is invalid </code></pre> <p>I want to know how but also why. What is the type of "hello"? How does casting works on Rust?</p>
NeutralinoJS and Tauri backend services
<p>I have used Electron for many years and like the fact that I can deliver a frontend app that has a bunch of backend services (connections to databases etc) that can be bundled in a dmg.</p> <p>Electron is however a bit heavyweight and I have been looking at NeutralinoJs and Tauri to see if I can do the same. I've tried NeutralinoJs and it's certainly good for bundling a frontend app but it appears not have any mechanism for writing backend services and being written in C++, I suspect this is unlikely to happen.</p> <p>Does Tauri allow you to write backend services in Rust - I can't tell from the documentation.</p>
Error: Could not find main or io in tokio, invalid return type `impl Future`
<p>I'm on my way of converting to Rust from the ML family, but I'm finding it hard at some strange places I'm not used to having problems.</p> <p>I'm trying to use <code>hyper</code> for http handling but can't seem to get <code>tokio</code> to work.</p> <p>I have tried to copy paste this <a href="https://github.com/hyperium/hyper/blob/master/examples/client.rs" rel="nofollow noreferrer">example</a>:</p> <pre class="lang-rust prettyprint-override"><code>use hyper::{body::HttpBody as _, Client}; use tokio::io::{self, AsyncWriteExt as _}; type Result&lt;T&gt; = std::result::Result&lt;T, Box&lt;dyn std::error::Error + Send + Sync&gt;&gt;; #[tokio::main] async fn main() -&gt; Result&lt;()&gt; { // ... fetch_url(url).await } async fn fetch_url(url: hyper::Uri) -&gt; Result&lt;()&gt; { // ... Ok(()) } </code></pre> <p>Here is my <code>Cargo.toml</code>:</p> <pre><code>[package] name = &quot;projectname&quot; version = &quot;0.1.0&quot; authors = [&quot;username&quot;] edition = &quot;2018&quot; [dependencies] hyper = &quot;0.14.4&quot; tokio = &quot;1.2.0&quot; </code></pre> <p>It is complaining that it can't find the <code>io</code> crate, and that <code>main</code> has an invalid type <code>impl Future</code>, and that it can't find <code>main</code> in <code>tokio</code>:</p> <pre class="lang-none prettyprint-override"><code>error[E0433]: failed to resolve: could not find `main` in `tokio` --&gt; src/main.rs:9:10 | 9 | #[tokio::main] | ^^^^ could not find `main` in `tokio` error[E0277]: `main` has invalid return type `impl Future` --&gt; src/main.rs:10:20 | 10 | async fn main() -&gt; Result&lt;()&gt; { | ^^^^^^^^^^ `main` can only return types that implement `Termination` error[E0432]: unresolved import `hyper::Client` --&gt; src/main.rs:3:34 | 3 | use hyper::{body::HttpBody as _, Client}; | ^^^^^^ no `Client` in the root error[E0425]: cannot find function `stdout` in module `io` --&gt; src/main.rs:45:13 | 45 | io::stdout().write_all(&amp;chunk).await?; | ^^^^^^ not found in `io` | error[E0432]: unresolved import `tokio::io::AsyncWriteExt` --&gt; src/main.rs:4:23 | 4 | use tokio::io::{self, AsyncWriteExt as _}; | -------------^^^^^ | | | no `AsyncWriteExt` in `io` | help: a similar name exists in the module: `AsyncWrite` </code></pre> <p>Is <code>#[tokio::main]</code> and <code>client</code> not in hyper?</p>
Who borrowed a variable?
<p>I'm fighting with the borrow checker. I have two similar pieces of code, one working as I expect, and the other not.</p> <p>The one that works as I expect:</p> <pre><code>mod case1 { struct Foo {} struct Bar1 { x: Foo, } impl Bar1 { fn f&lt;'a&gt;(&amp;'a mut self) -&gt; &amp;'a Foo { &amp;self.x } } // only for example fn f1() { let mut bar = Bar1 { x: Foo {} }; let y = bar.f(); // (1) 'bar' is borrowed by 'y' let z = bar.f(); // error (as expected) : cannot borrow `bar` as mutable more // than once at a time [E0499] } fn f2() { let mut bar = Bar1 { x: Foo {} }; bar.f(); // (2) 'bar' is not borrowed after the call let z = bar.f(); // ok (as expected) } } </code></pre> <p>The one that doesn't:</p> <pre><code>mod case2 { struct Foo {} struct Bar2&lt;'b&gt; { x: &amp;'b Foo, } impl&lt;'b&gt; Bar2&lt;'b&gt; { fn f(&amp;'b mut self) -&gt; &amp;'b Foo { self.x } } fn f4() { let foo = Foo {}; let mut bar2 = Bar2 { x: &amp;foo }; bar2.f(); // (3) 'bar2' is borrowed as mutable, but who borrowed it? let z = bar2.f(); // error: cannot borrow `bar2` as mutable more than once at a time [E0499] } } </code></pre> <p>I hoped I could call <code>Bar2::f</code> twice without irritating the compiler, as in case 1.</p> <p>The question is in the comment (3): who borrowed <code>bar2</code>, whereas there is no affectation? </p> <p>Here's what I understand: </p> <ol> <li><p>In case 1, <code>f2</code> call: the lifetime parameter <code>'a</code> is the one of the receiving <code>&amp;Foo</code> value, so this lifetime is empty when there is no affectation, and <code>bar</code> is not borrowed after the <code>Bar1::f</code> call;</p></li> <li><p>In case 2, <code>bar2</code> borrows <code>foo</code> (as immutable), so the lifetime parameter <code>'b</code> in <code>Bar2</code> struct is the <code>foo</code> reference lifetime, which ends at the end of <code>f4</code> body. Calling <code>Bar2::f</code> borrows <code>bar2</code> for that lifetime, namely to the end of <code>f4</code>.</p></li> </ol> <p>But the question is still: who borrowed <code>bar2</code>? Could it be <code>Bar2::f</code>? How <code>Bar2::f</code> would hold the borrowed ownership after the call? What am I missing here?</p> <p>I'm using Rust 1.14.0-nightly (86affcdf6 2016-09-28) on x86_64-pc-windows-msvc.</p>
Performance penalty of using clone_from_slice() instead of copy_from_slice()?
<p>In Rust, there are two methods to update the content of a slice from another slice: <a href="https://doc.rust-lang.org/std/primitive.slice.html#method.clone_from_slice" rel="nofollow noreferrer"><code>clone_from_slice()</code></a> and <a href="https://doc.rust-lang.org/std/primitive.slice.html#method.copy_from_slice" rel="nofollow noreferrer"><code>copy_from_slice()</code></a>. The behavior of these two functions are unsurprising - the first does a clone and expects the type to implement <code>Clone</code>, while the second does a copy and expects the type to implement <code>Copy</code>.</p> <p>However, it surprises me that the documentation for <code>clone_from_slice</code> says this: &quot;If <code>T</code> implements <code>Copy</code>, it can be more performant to use <code>copy_from_slice</code>.&quot; It is surprising that there should be a performance difference here. If <code>T</code> implements <code>Copy</code>, then <code>.clone()</code> is required to be equivalent to copying bits; however since the compiler knows what type <code>T</code> is, it should be able to figure out if it can do a bitwise copy even if I use <code>clone_from_slice</code>.</p> <p>So where does the performance inefficiency arise from?</p>
Implement a trait for a generic trait
<p>In Rust, how to implement a Trait for a generic trait?</p> <pre class="lang-rust prettyprint-override"><code>trait One&lt;S&gt; {} trait Two {} // fails because S isn't contrained impl&lt;S, T&gt; Two for T where T: One&lt;S&gt; {} </code></pre> <hr /> <p>To clarify, I'm trying to provide the <code>BitAnd</code> trait for a generic <code>Select</code> trait.</p> <pre class="lang-rust prettyprint-override"><code>struct Thing&lt;S&gt; { field: S, } trait Select&lt;S&gt; { fn select(&amp;self, thing: &amp;Thing&lt;S&gt;) -&gt; bool; } struct SelectUnion&lt;S&gt; (Box&lt;dyn Select&lt;S&gt;&gt;, Box&lt;dyn Select&lt;S&gt;&gt;); // fails because S isn't contrained impl&lt;S, T&gt; std::ops::BitAnd for T where T: Select&lt;S&gt; { type Output = SelectUnion&lt;S&gt;; fn bitand(self, rhs: Self) -&gt; Self::Output { SelectUnion(Box::new(self), Box::new(rhs)) } } </code></pre>
Can I export an already existing docker container into a dockerfile?
<p>I may have not followed best practices, I believe, and I am kinda trying to correct myself</p> <p>I have created a container starting from the Rust docker image for a project. I have been using this container more like a small VM rather than a container. Through the docker dashboard I start it every morning and work on it, either by <code>docker -it exec my-container bash</code> or using <code>docker exec</code> from scripts. Since I created it from the Rust image, I have added users, installed crates and packages etc.</p> <p><strong>Is there a way to create a Dockerfile from an existing docker container, that will contain all this, so I can use it to create ephemeral copies of this container to run specific jobs?</strong></p>
Rust error: unable to infer enough type information to locate the impl of the trait
<p>I don't quite understand why this is ok</p> <pre><code>use std::num; fn main() { let mut p_: int = num::pow(16, 2); let mut p: f64 = p_ as f64; } </code></pre> <p>but this is failing</p> <pre><code>use std::num; fn main() { let mut p: f64 = num::pow(16, 2) as f64; } </code></pre> <p>with error</p> <pre><code>error: unable to infer enough type information to locate the impl of the trait `core::num::Int` for the type `_`; type annotations required let mut p: f64 = num::pow(16, 2) as f64; ^~~~~~~~ </code></pre> <p>For the sake of context, this is what I'm trying to do (pi approximation):</p> <pre><code>fn main() { let mut pi: f64 = 0.0; let precision: int = 10; for i in range(0, precision) { let k = i as f64; let mut pi16: int = num::pow(16, i as uint); let mut p16: f64 = pi16 as f64; pi += 1.0/p16 * (4.0/(8.0 * k + 1.0) - 2.0/(8.0 * k + 4.0) - 1.0/(8.0 * k + 5.0) - 1.0/(8.0 * k + 6.0)); } } </code></pre> <p>I'm using <code>rustc 0.13.0-nightly (f09279395 2014-11-17 17:22:06 +0000)</code></p>
Is there a way to allow an unknown enum tag when deserializing with Serde?
<p>I'm deserializing a tagged enum:</p> <pre><code>#[derive(Deserialize)] enum Foo { A(A), B(B), C(C), } </code></pre> <p>If Serde encounters a tag that isn't <code>A</code>, <code>B</code> or <code>C</code>, then it will throw an error. Is there any way to add a catch-all variant for unknown tags? I'd be happy if it only records the tag:</p> <pre class="lang-rust prettyprint-override"><code>#[derive(Deserialize)] enum Foo { A(A), B(B), C(C), #[serde(unknown_tag)] Unknown(String), } </code></pre>
Collapse amp-accordion with close button within accordiandiv
<p>I have an AMP-HTML page where the user can expand an amp-accordion but the list is quite long. To close the accordion the user must scroll way up to the top title to close. I am hoping to add a close button at the bottom of the list that will collapse the accordion. I can't use Jquery or inline javascript because it is AMP valid. Here is what I have tried. I know you can do this on a normal div, just having trouble getting it to work within an accordion. Thanks for any help you can provide. </p> <pre><code>&lt;amp-accordion class="accordion"&gt; &lt;section id="topranked"&gt; &lt;h4 class="bg-rust-light"&gt;Top places in Boise&lt;i class="fa fa-plus"&gt;&lt;/i&gt;&lt;/h4&gt; &lt;div class="accordiondiv" id="toprankedhide"&gt; &lt;p class="half-bottom center big-text"&gt;&lt;i class="fa fa-star fa-2x color-ship-dark"&gt;&lt;/i&gt;&lt;br&gt; Based on &lt;strong&gt;32,000 reviews&lt;/strong&gt; from our guests&lt;/p&gt; &lt;a class="button bg-gray-light border-gray-dark button100 big-text" href="/official.asp?ID=1"&gt;Company1&lt;/a&gt;&lt;br&gt;&lt;a class="button bg-gray-light border-gray-dark button100 big-text" href="/official.asp?ID=1"&gt;Company2&lt;/a&gt;&lt;br&gt; &lt;a class="button bg-gray-light border-gray-dark button100 big-text" href="/official.asp?ID=1"&gt;Company3&lt;/a&gt; &lt;button on="tap:toprankedhide.hide"&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/section&gt; &lt;/amp-accordion&gt; </code></pre>
How to get a hex string from Rust's MD-5 (MD5) crate?
<p>According to this RFC about WWW Authentication (used in HTTTP) <a href="https://www.rfc-editor.org/rfc/rfc2617#page-7" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc2617#page-7</a>,</p> <blockquote> <p>For the purposes of this document, an MD5 digest of 128 bits is<br /> represented as 32 ASCII printable characters. The bits in the 128 bit digest are converted from most significant to least significant bit,<br /> four bits at a time to their ASCII presentation as follows. Each four bits is represented by its familiar hexadecimal notation from the<br /> characters 0123456789abcdef. That is, binary 0000 gets represented by the character '0', 0001, by '1', and so on up to the representation<br /> of 1111 as 'f'.</p> </blockquote> <p>Rust's <a href="https://crates.io/crates/md-5" rel="nofollow noreferrer">MD5 crate</a> implements the Digest trait: <a href="https://docs.rs/digest/0.9.0/digest/trait.Digest.html" rel="nofollow noreferrer">https://docs.rs/digest/0.9.0/digest/trait.Digest.html</a> which digests to a GenericArray which consists of <code>8</code> 16-bit slices.</p> <p>How do I convert for this hash format from RFC? Why doesn't the md-5 crate has a simple feature that displays the digest as hexadecimal values?</p> <p>The crate <code>literal_hex</code> does the opposite: converts from String of hexadecimal concatenated values to bytes.</p>
Using FnMut() closures in a static function
<p><strong>Background:</strong> I'm trying to avoid the use of <code>Mutex</code>/<code>RefCell</code>/<code>Option</code> dance in an interrupt handler for an embedded system. I do not want to use the heap (and I don't think it should be necessary -- but feel free to show me wrong). I can't use <code>std</code>. I've looked at <code>cortex-m-rtfm</code> and it's neat, but pretty invasive. And anyway, this is a bit of a learning exercise. If it works out, I would prefer to use closures to handle interrupts since it feels closer to bare Rust. I am a total Rust newbie -- I've been working with it for about a week. I have tried a <em>lot</em> of different variants of this as I've read through documentation, re-read the Rust book, blog posts, etc.,. I cannot figure what I'm doing wrong here.</p> <p>Here's the sample code. Questions to follow:</p> <pre><code>use core::cell::UnsafeCell; pub struct Handler&lt;'a&gt; { h: UnsafeCell&lt;&amp;'a dyn FnMut()&gt;, } impl&lt;'a&gt; Handler&lt;'a&gt; { pub fn new&lt;T: FnMut()&gt;(closure: &amp;'a dyn FnMut()) -&gt; Self { Handler { h: UnsafeCell::new(closure), } } pub fn call(&amp;self) { unsafe { // NOTE: type returned by `self.h.get()` is // `*mut &amp;'a (dyn std::ops::FnMut() + 'a)` let h: *mut FnMut() = self.h.get(); h(); } } } unsafe impl&lt;'a&gt; Sync for Handler&lt;'a&gt; {} fn default_handler() {} static HANDLER: Handler = Handler { h: UnsafeCell::new(&amp;default_handler), }; #[test] fn call_handler() { let mut a: u32 = 0; let foo = move || a += 1; let mut handler = Handler::new(&amp;foo); handler.call(); a += 2; // Shouldn't this cause compilation failure because `a` // was moved into the closure above? assert_eq!(a, 1); } </code></pre> <p><strong>Error</strong></p> <pre><code>error[E0618]: expected function, found `*mut dyn std::ops::FnMut()` --&gt; src/lib.rs:19:13 | 18 | let h: *mut FnMut() = self.h.get(); | - `*mut dyn std::ops::FnMut()` defined here 19 | h(); | ^-- | | | call expression requires function error[E0277]: expected a `std::ops::Fn&lt;()&gt;` closure, found `(dyn std::ops::FnMut() + 'a)` --&gt; src/lib.rs:18:35 | 18 | let h: *mut FnMut() = self.h.get(); | ^^^^^^^^^^^^ expected an `Fn&lt;()&gt;` closure, found `(dyn std::ops::FnMut() + 'a)` | = help: the trait `std::ops::Fn&lt;()&gt;` is not implemented for `(dyn std::ops::FnMut() + 'a)` = note: wrap the `(dyn std::ops::FnMut() + 'a)` in a closure with no arguments: `|| { /* code */ } = note: required because of the requirements on the impl of `std::ops::FnMut&lt;()&gt;` for `&amp;'a (dyn std::ops::FnMut() + 'a)` = note: required for the cast to the object type `dyn std::ops::FnMut()` </code></pre> <p><strong>Explanation:</strong> Hopefully, my intentions are obvious: I'll set up the closure for <code>HANDLER</code> in <code>main</code>, before going into a busy-loop that never exits. The closure will mutably borrow the stuff the interrupt handler needs for its operation, preventing its use in other contexts. Since <code>main</code> never exits, stack-allocated variables within it are effectively <code>'static</code>, so there shouldn't be a problem with referencing them at any point after the closure is set. The interrupt handler itself (not shown) will simply call the closure to do its work. To work around the storage of a closure (which is not <code>Sized</code>) in a static, I need to store a reference to the closure. <code>UnsafeCell</code> isn't necessarily required, but since I'm using <code>FnMut()</code> its referents need to be mutable, which runs into <code>statics require immutable values</code> when trying to set up <code>default_handler</code> during the creation of a <code>static mut HANDLER</code>.</p> <p><strong>Questions:</strong></p> <ol> <li><p>As posted, this code doesn't compile. For some reason, the assignment <code>let h: *mut FnMut() = self.h.get()</code> tells me that it <code> expected an Fn&lt;()&gt; closure, found (dyn std::ops::FnMut() + 'a)</code>. Well, I know why it found that type. But why is it expecting <code>Fn&lt;()&gt;</code>?</p></li> <li><p>In the <code>call_handler</code> test, why is this compiling at all? The <code>foo</code> closure <code>move</code>s its captured variable <code>a</code>. How is it possible to mutate it after the closure definition? When I've tried this code with a type that doesn't implement <code>Copy</code>, it fails as expected, but I'm frankly surprised that trait matters. Isn't the point that <code>foo</code> owns <code>a</code> now?</p></li> </ol> <p>I realize there are potential issues with changing <code>HANDLER.h</code> at arbitrary points in the code, but I will worry about solving those later, after there's a viable proof-of-concept.</p>
pattern matching on String in Rust Language
<p>Is possible to parse the <code>&lt;path&gt;</code> part from <code>GET /&lt;path&gt; HTTP/1.1</code> using pattern matching, or anything gracefully rather than direct string manipulation such as <code>split</code> or <code>slice</code> </p>
Insert constructed string into Vec in Rust
<p>Right now I am writing a program where I am updating a <code>Vec</code> with a string constructed based on conditions in a for loop. A (very contrived) simplified form of what I'm trying to do is the following:</p> <pre class="lang-rust prettyprint-override"><code>fn main() { let mut arr = vec!["_"; 5]; for (i, chr) in "abcde".char_indices() { arr[i] = &amp;chr.to_string().repeat(3); } } </code></pre> <p>However, I am getting the error <code>temporary value dropped while borrowed</code>. Any pointers on what to do here?</p>
How to use Rust's async/await syntax in WASI
<p>I would like to compile the following code with <a href="https://github.com/bytecodealliance/cargo-wasi" rel="nofollow noreferrer">cargo-wasi</a>.</p> <pre class="lang-rust prettyprint-override"><code>// reqwest = { version = &quot;0.11&quot;, features = [&quot;json&quot;] } // tokio = { version = &quot;1&quot;, features = [&quot;full&quot;] } use std::collections::HashMap; #[tokio::main] async fn main() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; { let resp = reqwest::get(&quot;https://httpbin.org/ip&quot;) .await? .json::&lt;HashMap&lt;String, String&gt;&gt;() .await?; println!(&quot;{:#?}&quot;, resp); Ok(()) } </code></pre> <p>After trying to compile it, I got the following error because <a href="https://github.com/tokio-rs/mio/issues/1346" rel="nofollow noreferrer">mio doesn't currently support WASI</a></p> <pre><code>$ cargo wasi run Compiling mio v0.7.9 Compiling parking_lot v0.11.1 Compiling serde_json v1.0.64 Compiling idna v0.2.2 error[E0432]: unresolved import `crate::sys::IoSourceState` --&gt; /home/ducaale/.cargo/registry/src/github.com-1ecc6299db9ec823/mio-0.7.9/src/io_source.rs:12:5 | 12 | use crate::sys::IoSourceState; | ^^^^^^^^^^^^^^^^^^^^^^^^^ no `IoSourceState` in `sys` ... errors omitted </code></pre> <p>I did some research and none of the <a href="https://github.com/wapm-packages/rust-wasi-example/blob/master/src/main.rs" rel="nofollow noreferrer">examples</a> I found so far were utilizing async/await. Is there something I could replace <code>tokio</code> with so my code compiles in WASI?</p>
Why is there a difference regarding lifetime elision of impl trait function arguments between async and non-async functions?
<p>This code compiles:</p> <pre class="lang-rust prettyprint-override"><code>async fn foo(_: impl Iterator&lt;Item = &amp;u32&gt;) {} </code></pre> <p>However, removing the <code>async</code>, it does not work anymore:</p> <pre class="lang-rust prettyprint-override"><code>fn foo(_: impl Iterator&lt;Item = &amp;u32&gt;) {} </code></pre> <p>Instead, it results in:</p> <pre class="lang-none prettyprint-override"><code>error[E0106]: missing lifetime specifier --&gt; src/lib.rs:1:32 | 1 | fn foo(_: impl Iterator&lt;Item = &amp;u32&gt;) {} | ^ expected named lifetime parameter | help: consider introducing a named lifetime parameter | 1 | fn foo&lt;'a&gt;(_: impl Iterator&lt;Item = &amp;'a u32&gt;) {} | ^^^^ ^^^ </code></pre> <p>(<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=1600f9f8c737e04c38e05c2a6348333f" rel="noreferrer">Playground</a>)</p> <p>Why is there a difference regarding lifetime elision between <code>async</code> and non-<code>async</code> functions? This makes no sense to me. It seems like the non-<code>async</code> case could easily leave out the lifetime as well. It's just introducing another anonymous input lifetime.</p>
How can I get a slice from an Option in Rust?
<p>I have an <code>Option</code> in Rust, and I need to use it in a function that accepts a slice. How do I get a slice from an <code>Option</code> where <code>Some(x)</code>'s slice has one element and <code>None</code>'s has zero elements?</p>
How can I get access to the current and previous item in a linked list?
<p>I'm writing a map generator in Rust which will split the world into sections and then within those sections create rooms in order to connect these rooms. What I would normally do is have a list and then as I iterate through the list get the parent (if there is one) and then run some code to connect these rooms.</p> <p>I'm struggling with the traversing through a list and getting the parent.</p> <p>Here are the data structures I currently have:</p> <pre class="lang-rust prettyprint-override"><code>struct MapSectionPosition { x: f32, y: f32, } struct MapSectionRect { top_left: MapSectionPosition, top_right: MapSectionPosition, bottom_right: MapSectionPosition, bottom_left: MapSectionPosition, } struct MapSection { width: f32, height: f32, points: MapSectionRect, } struct RoomExit { position: MapSectionPosition, } struct Room { width: f32, height: f32, exit: RoomExit, } </code></pre> <p>At the moment I'm using a linked list:</p> <pre class="lang-rust prettyprint-override"><code>let mut rooms: LinkedList&lt;Room&gt; = LinkedList::new(); let room = Room { width: section.width / 4.0, height: section.height / 4.0, exit: RoomExit { position: MapSectionPosition { x: 20.0, y: 20.0 }, }, }; rooms.push_back(room); </code></pre> <p>I'm struggling to both iterate and get the parent, so I'm thinking this might not be the right data structure.</p> <p>With some playing around I've found a hacky solution. Hopefully this will better illustrate what I'm trying to do and if there is something more elegant.</p> <pre><code>let mut previous_room: Option&lt;&amp;Room&gt; = None; for room in rooms.iter() { match previous_room { Some(p_room) =&gt; { println!("previous {}", p_room.width); println!("current {}", room.width); println!("connected"); }, None =&gt; { println!("no previous room"); } } previous_room = Some(room); } </code></pre> <p><strong>Something a little more elegant</strong></p> <p>If rooms are a slice, then we can use the <code>windows</code> method to create an iterator to access the data in question.</p> <pre><code>let mut iter = rooms[..].windows(2); while let Some([prev, next]) = iter.next() { println!("prev - {}", prev.width); println!("next - {}", next.width); println!("done...") } </code></pre> <p>This has been answered before in <a href="https://stackoverflow.com/q/42134874/155423">Are there equivalents to slice::chunks/windows for iterators to loop over pairs, triplets etc?</a></p>
All messages in queue get allocated to a single subscriber
<p>I have sent some 10000 messages to a persistent RabbitMQ queue, all these messages are in &quot;Ready&quot; state. The code below sleeps for 10 seconds when processing each message. As soon as I run the rust application that calls the function below, all these messages in the queue have their status moved from &quot;Ready&quot; to &quot;Unacked&quot; almost instantly. The code continues to process the messages one message at a time.</p> <p>If I start another instance of that runs the code below, no messages are dispatched to this instance unless I terminate the first application.</p> <p>The behaviour I would like to have is subscribers at most only receive one message at a time and only get to obtain the next message once they've acked the current one.</p> <p>What configuration should I change?</p> <pre><code>use lapin::{options::*, Connection, ConnectionProperties, Result}; use futures_util::stream::StreamExt; //use std::future::Future; use tracing::info; use slog::Drain; pub fn lapin_test_consumer()-&gt;std::result::Result&lt;i64, Box&lt;std::io::Error&gt;&gt; { //env_logger::init(); let log_file_name:&amp;str=&quot;/tmp/lapin_test_consumer.log&quot;; let log_file_path=std::path::Path::new(&amp;log_file_name); let dir_file_path=log_file_path.parent().unwrap(); std::fs::create_dir_all(dir_file_path).unwrap(); let log_file_handler_option = std::fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(log_file_name) //.unwrap() ; let log_file_handler=match log_file_handler_option { Ok(f)=&gt;f ,Err(err)=&gt;{ println!(&quot;{:?}&quot;, err); panic!(&quot;Unable to open the log file '{}', '{:?}'&quot;,log_file_name,err); } }; let my_log_drain = slog_async::Async::new( slog::Duplicate::new( slog::Filter::new( slog_term::FullFormat::new( slog_term::PlainSyncDecorator::new(log_file_handler,) ) .use_file_location() .build() , |record: &amp;slog::Record| { record.level().is_at_least(slog::Level::Debug) } ) //,slog_term::FullFormat::new(slog_term::PlainSyncDecorator::new(std::io::stdout())).build() ,slog::Duplicate::new( slog::Filter::new( slog_term::FullFormat::new( slog_term::PlainSyncDecorator::new(std::io::stderr(),) ) .use_file_location() .build() , //|record: &amp;slog::Record| record.level().is_at_least(slog::Level::Warning) |record: &amp;slog::Record| { record.level().is_at_least(slog::Level::Debug) } ) //,slog_term::FullFormat::new(slog_term::PlainSyncDecorator::new(std::io::stdout())).build() ,slog_term::FullFormat::new(slog_term::TermDecorator::new().build()).use_file_location().build() ) ).fuse() ) .build() .fuse() ; let my_slog_logger=slog::Logger::root(my_log_drain, slog::o!(&quot;n&quot; =&gt; env!(&quot;CARGO_PKG_NAME&quot;),&quot;v&quot; =&gt; env!(&quot;CARGO_PKG_VERSION&quot;))); if std::env::var(&quot;RUST_LOG&quot;).is_err() { std::env::set_var(&quot;RUST_LOG&quot;, &quot;info&quot;); } let addr:String = std::env::var(&quot;AMQP_ADDR&quot;).unwrap_or_else( |_|{ format!(&quot;amqp://{}:{}@{}:{}/{}?heartbeat=0&quot; ,&quot;abcd&quot;//aMQPJobUser ,&quot;abcd&quot;//aMQPJobPasswd ,&quot;somewhere.com&quot;//aMQPJobHost ,5672//aMQPJobPort ,&quot;lapin_test.test&quot;//aMQPJobVirtualHost ).into() } ); let amqp_conn_url:&amp;str=&amp;addr.as_str(); //see &quot;https://docs.rs/lapin/1.8.0/lapin/struct.Consumer.html&quot; let res: std::result::Result&lt;i64, Box&lt;std::io::Error&gt;&gt; = async_global_executor::block_on(async { let sleep_duration_ms:u64=10000u64; let conn_result:std::result::Result&lt;lapin::Connection, lapin::Error&gt; = Connection::connect( &amp;amqp_conn_url, ConnectionProperties::default().with_default_executor(2),//set the number of threads ) .await; let conn:lapin::Connection=match conn_result{ Err(err)=&gt;{ let bt=backtrace::Backtrace::new(); let log_message=format!(&quot;&gt;&gt;&gt;&gt;&gt;At lapin_test_publisher(), pos 1b, some error has been encountered while trying to establish AMQP connection '{:?}', error is:'{:?}', backtrace is '{:?}'&quot;,&amp;amqp_conn_url,&amp;err,&amp;bt); slog::error!(my_slog_logger,&quot;{}&quot;,log_message); let custom_error=std::io::Error::new(std::io::ErrorKind::Other, &amp;log_message.to_string()[..]); return std::result::Result::Err(Box::new(custom_error)); } Ok(conn2)=&gt;{info!(&quot;CONNECTED&quot;);conn2} }; let mut message_cnt:i64=0i64;let _some_i64:i64=message_cnt; let channel_a_result:Result&lt;lapin::Channel&gt;=conn.create_channel().await; let channel_a:lapin::Channel=match channel_a_result{ Err(err)=&gt;{ let bt=backtrace::Backtrace::new(); let log_message=format!(&quot;&gt;&gt;&gt;&gt;&gt;At lapin_test_consumer(), pos 1b, some error has been encountered while trying to obtain a channel from AMQP connection '{:?}', error is:'{:?}', backtrace is '{:?}'&quot;,&amp;amqp_conn_url,&amp;err,&amp;bt); slog::error!(my_slog_logger,&quot;{}&quot;,log_message); let custom_error=std::io::Error::new(std::io::ErrorKind::Other, &amp;log_message.to_string()[..]); return std::result::Result::Err(Box::new(custom_error)); } Ok(channel)=&gt;{channel} }; channel_a .exchange_declare( &quot;my_direct_exchange&quot; ,lapin::ExchangeKind::Direct ,lapin::options::ExchangeDeclareOptions{ passive:false ,durable:true ,auto_delete:false ,internal:false ,nowait:false } ,lapin::types::FieldTable::default()//see &quot;https://docs.rs/amq-protocol-types/6.1.0/amq_protocol_types/struct.FieldTable.html&quot; ) ; let queue = channel_a .queue_declare( &quot;hello.persistent&quot;//:&amp;str queue name ,lapin::options::QueueDeclareOptions{ passive:false, durable:true, exclusive:false, auto_delete:false, nowait:false, } ,lapin::types::FieldTable::default()//see &quot;https://docs.rs/amq-protocol-types/6.1.0/amq_protocol_types/struct.FieldTable.html&quot; ) .await .expect(&quot;queue_declare&quot;) ; channel_a .queue_bind( &quot;hello.persistent&quot; ,&quot;my_direct_exchange&quot; ,&quot;hello.persistent&quot; , lapin::options::QueueBindOptions{ nowait:false } ,lapin::types::FieldTable::default()//see &quot;https://docs.rs/amq-protocol-types/6.1.0/amq_protocol_types/struct.FieldTable.html&quot; ) ; let consumer_a_result:Result&lt;lapin::Consumer&gt;=channel_a .basic_consume( &quot;hello.persistent&quot;, &quot;my_consumer&quot;, lapin::options::BasicConsumeOptions{ no_local: true,//see &quot;https://www.rabbitmq.com/amqp-0-9-1-reference.html#domain.no-local&quot; no_ack: false,//see &quot;https://www.rabbitmq.com/amqp-0-9-1-reference.html#domain.no-ack&quot; &quot;If this field is set the server does not expect acknowledgements for messages. That is, when a message is delivered to the client the server assumes the delivery will succeed and immediately dequeues it. This functionality may increase performance but at the cost of reliability. Messages can get lost if a client dies before they are delivered to the application.&quot; exclusive: false, nowait: false,//see &quot;https://www.rabbitmq.com/amqp-0-9-1-reference.html#domain.no-wait&quot; &quot;If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception.&quot; }, lapin::types::FieldTable::default(), ) .await; let mut consumer_a:lapin::Consumer=match consumer_a_result{ Err(err)=&gt;{ let bt=backtrace::Backtrace::new(); let log_message=format!(&quot;&gt;&gt;&gt;&gt;&gt;At lapin_test_consumer(), pos 1b, some error has been encountered while trying to obtain a consumer from AMQP connection '{:?}', error is:'{:?}', backtrace is '{:?}'&quot;,&amp;amqp_conn_url,&amp;err,&amp;bt); slog::error!(my_slog_logger,&quot;{}&quot;,log_message); let custom_error=std::io::Error::new(std::io::ErrorKind::Other, &amp;log_message.to_string()[..]); return std::result::Result::Err(Box::new(custom_error)); //return Err(err); } Ok(consumer)=&gt;{consumer} }; while let Some(delivery) = consumer_a.next().await { let (channel2, delivery2) = delivery.expect(&quot;error in consumer&quot;); message_cnt+=1; slog::info!(my_slog_logger,&quot;------------------------------------------------------------------, message_cnt is:{}&quot;,&amp;message_cnt); let s:String = match String::from_utf8(delivery2.data.to_owned()) {//delivery.data is of type Vec&lt;u8&gt; Ok(v) =&gt; v, Err(e) =&gt; panic!(&quot;Invalid UTF-8 sequence: {}&quot;, e), }; let log_message:String=format!(&quot;message_cnt is:{}, delivery_tag is:{}, exchange is:{}, routing_key is:{}, redelivered is:{}, properties is:'{:?}', received data is:'{:?}'&quot; ,&amp;message_cnt ,&amp;delivery2.delivery_tag ,&amp;delivery2.exchange ,&amp;delivery2.routing_key ,&amp;delivery2.redelivered ,&amp;delivery2.properties ,&amp;s ); slog::info!(my_slog_logger,&quot;{}&quot;,log_message); std::thread::sleep(std::time::Duration::from_millis(sleep_duration_ms)); slog::info!(my_slog_logger,&quot;After {}ms sleep.&quot;,sleep_duration_ms); channel2 .basic_ack(delivery2.delivery_tag, BasicAckOptions::default()) .await .expect(&quot;ack&quot;) ; } Ok(message_cnt) } ); res } </code></pre>
What's the difference between &String and &str in a function signature?
<p>Considering the following program:</p> <pre><code>fn main() { let s = String::from(&quot;helloworld&quot;); // This works fine println!(&quot;The first word is: {}&quot;, first_word(&amp;s)); // This won't compile println!(&quot;The first word is: {}&quot;, first_word(&amp;s[..])); // This works fine println!(&quot;The first word is: {}&quot;, first_word1(&amp;s)); // This works fine println!(&quot;The first word is: {}&quot;, first_word1(&amp;s[..])); } fn first_word(s: &amp;String) -&gt; &amp;str { let bytes = s.as_bytes(); for (i, &amp;item) in bytes.iter().enumerate() { if item == b' ' { return &amp;s[0..i]; } } s } fn first_word1(s: &amp;str) -&gt; &amp;str { let bytes = s.as_bytes(); for (i, &amp;item) in bytes.iter().enumerate() { if item == b' ' { return &amp;s[0..i]; } } &amp;s[..] } </code></pre> <p>It seems that for a &amp;str parameter, you can use either a &amp;String or a &amp;str as argument, but for a &amp;String parameter, only &amp;String is allowed. It also seems that if a function returns &amp;str in its signature, it can return either a &amp;String or a &amp;str, the caller of the function won't see any difference.</p> <p>So my question is, what is the difference between &amp;String and &amp;str, in parameter types and return types of rust function signatures?</p>
How to store a callback in a struct that can change the struct's internal state?
<p>In one of my projects, I would like to store a function pointer used as a callback to change the state of a struct. I've tried different things, but always encountered errors.</p> <p>Consider the following situation (<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=8112baa75783684f78c52e4a63b6ce17" rel="nofollow noreferrer">playground</a>):</p> <pre class="lang-rust prettyprint-override"><code>struct CallbackStruct { callback: fn(i32) -&gt; i32, } struct MainStruct { pub callback_struct: Vec&lt;CallbackStruct&gt;, pub intern_state: i32, } impl MainStruct { pub fn new() -&gt; MainStruct { let result = MainStruct { callback_struct: Vec::new(), intern_state: 0, }; // push a new call back struct result.callback_struct.push(CallbackStruct{callback: result.do_stuff}); return result; } pub fn do_stuff(&amp;mut self, i: i32) -&gt; i32 { self.intern_state = i * 2 + 1; self.intern_state } } fn main() { let my_struct = MainStruct::new(); } </code></pre> <p>Here, I'm trying to keep a callback to the <code>MainStruct</code>, that can change it's internal state. This callback will only be stored by other structs owned by this main structure, so I don't think I'm having lifetimes issues - as long as the callback exists, the main struct does as well as it kind of own it.</p> <p>Now, I'm wondering if having such a callback (with the <code>&amp;mut self</code> reference) isn't a borrow of the main struct, preventing me from having multiple of them, or even keeping them?</p> <p>In the example, I'm keeping a <code>Vec</code> of the <code>CallbackStruct</code> because I may have different structs all having these kinds of callbacks.</p> <p>In c/c++, I can go with functions pointers, and I couldn't find a way to store such things in Rust.</p> <p>How would one implement such a thing?</p>
Is there a way to apply a UDF function returning multiple values in Rust polars?
<p>I'm trying to use polars to apply a function from another library across each row of an input. I can't find any examples or tests of using an Expr to apply a function, even when it has one return value; so I'm lost.</p> <p>It's taking an input dataframe with two float columns, and trying to append three columns as generated by a function with this form:</p> <pre><code>fn f(a: f64, b: f64) -&gt; (f64, f64, f64); </code></pre> <p>Is there a simple way to do this?</p>
Rust escaped unicode chars to string
<p>I'm querying an API over HTTP I'm getting back JSON data with following</p> <pre><code>... Dv\\u016fr Kr\\u00e1lov\\u00e9 nad Labem a okol\\u00ed 5\\u00a0km ...&quot;. </code></pre> <p>This is what I see when I open the same request in Firefox and show raw data and also when I try to println! the output in Rust.</p> <p>I would like Rust to rather interpret these into proper chars. I've tried following function which I've googled and it works partially but it fails for some chars</p> <pre><code> pub fn normalize(json: &amp;str) -&gt; core::result::Result&lt;String, Box&lt;dyn Error&gt;&gt; { let replaced : Cow&lt;'_, str&gt; = regex_replace_all!(r#&quot;\\u(.{4})&quot;#, json, |_, num: &amp;str| { let num: u32 = u32::from_str_radix(num, 16).unwrap(); let c: char = std::char::from_u32(num).unwrap(); c.to_string() }); Ok(replaced.to_string()) } </code></pre> <pre><code>Dvůr Králové nad Labem a okolí 5\u{a0}km </code></pre> <p>What's the proper way to handle such JSON data?</p>
How to store and use closures that use a common region of memory?
<p>I'm writing a piece of Rust code that simulates a small (typed) toy language with closures, but I'm not sure how I should store them in an <code>enum</code> so that they are still able to access/use a common heap when I evaluate the closures.</p> <p>I'd like the program's data to be stored on a heap, and I allow all of the closures to take in this heap as an argument in case it needs to allocate something, retrieve a value, etc. I'm okay if the closure code itself is dynamically allocated by Rust, but I want the pointers to the closures themselves to be in my <code>Heap</code> struct.</p> <p>I've tried storing the data as a function pointer (like <code>fn(usize, usize, &amp;mut Heap)</code>), as well as boxed closures (like <code>Box&lt;dyn FnMut(usize, &amp;mut Heap) -&gt; usize&gt;</code>), as well as a boxed pointer version with a lifetime argument (like <code>Box&lt;dyn FnMut(usize, &amp;mut Heap) -&gt; usize + 'a&gt;</code>) but I always seem to run into some issue with the borrow checker.</p> <p>Here is a simplified version of my code:</p> <pre><code>enum Val { Int(i32), Bool(bool), Lambda(Box&lt;dyn FnMut(usize, &amp;mut Heap) -&gt; usize&gt;), } struct Heap { mem: Vec&lt;Val&gt;, } impl Heap { fn alloc(&amp;mut self, v: Val) -&gt; usize { self.mem.push(v); self.mem.len() - 1 } fn get(&amp;self, i: usize) -&gt; &amp;Val { &amp;self.mem[i] } } fn apply(func: usize, arg: usize, heap: &amp;mut Heap) -&gt; usize { let closure = match heap.get(func) { Val::Lambda(x) =&gt; x, _ =&gt; panic!(), }; closure(arg, heap) } fn main() { let mut h = Heap { mem: vec![] }; // creating a closure let foo = Val::Lambda(Box::new(|a: usize, mut heap: &amp;mut Heap| -&gt; usize { let a_val = match heap.get(a) { Val::Int(x) =&gt; *x, _ =&gt; panic!(), }; heap.alloc(Val::Int(a_val * a_val)) })); let f = h.alloc(foo); // using the closure let a = h.alloc(Val::Int(3)); let b = apply(f, a, &amp;mut h); match h.get(b) { Val::Int(x) =&gt; println!("{}", x), _ =&gt; panic!(), }; } </code></pre> <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=0caf1ebe71767409db0a9f30c27d6c1a" rel="nofollow noreferrer">Rust playground</a></p> <p>The above code should output 9, but instead there is a borrow-checker error:</p> <pre class="lang-none prettyprint-override"><code>error[E0596]: cannot borrow `**closure` as mutable, as it is behind a `&amp;` reference --&gt; src/main.rs:27:5 | 23 | let closure = match heap.get(func) { | ------- help: consider changing this to be a mutable reference: `&amp;mut std::boxed::Box&lt;dyn for&lt;'r&gt; std::ops::FnMut(usize, &amp;'r mut Heap) -&gt; usize&gt;` ... 27 | closure(arg, heap) | ^^^^^^^ `closure` is a `&amp;` reference, so the data it refers to cannot be borrowed as mutable error[E0502]: cannot borrow `*heap` as mutable because it is also borrowed as immutable --&gt; src/main.rs:27:5 | 23 | let closure = match heap.get(func) { | ---- immutable borrow occurs here ... 27 | closure(arg, heap) | -------^^^^^^^^^^^ | | | mutable borrow occurs here | immutable borrow later used by call warning: variable does not need to be mutable --&gt; src/main.rs:34:47 | 34 | let foo = Val::Lambda(Box::new(|a: usize, mut heap: &amp;mut Heap| -&gt; usize { | ----^^^^ | | | help: remove this `mut` | = note: #[warn(unused_mut)] on by default </code></pre> <p>Is it possible to clone my closures / enum to mitigate this borrowing issue? I am not sure if this is possible due to the restrictions on <a href="https://doc.rust-lang.org/std/clone/trait.Clone.html" rel="nofollow noreferrer"><code>Clone</code></a> listed by the Rust documentation:</p> <blockquote> <p>"Closure types, if they capture no value from the environment or if all such captured values implement <code>Clone</code> themselves. Note that variables captured by shared reference always implement <code>Clone</code> (even if the referent doesn't), while variables captured by mutable reference never implement <code>Clone</code>."</p> </blockquote>
Reduce application binary size in debug mode
<p>When I compile GTK4 &quot;Hello World&quot; application in rust I get binary with size 192Mb for debug mode. I use old SSD and I worry about it's resource as I compile and debug very frequently. I tried <code>-C prefer-dynamic</code> flag, but size of binary become 188Mb only.</p> <p>Is this way to make application binary size much smaller?</p> <p>PS: I work in win10 and use MSYS2. PPS: I don't have problem with release build's size. With <code>-C link-arg=-s</code> and <code>lto = true</code> the size is about 200kb</p>
How do I detect .connect_pad_added() template = video_%u?
<p>Using the gstreamer Rust bindings, how can I test if a sometimes pad that has been added is from template <code>video_%u</code> or <code>audio_%u</code>?</p> <p>For example, using qtdemuxm, the following pad added is called once for video and once for audio </p> <pre><code>.connect_pad_added(move |demux, src_pad| { </code></pre> <p>according to the binding docs it seems </p> <pre><code>get_property_name_template(&amp;self) </code></pre> <p>but this fails </p> <pre><code>.connect_pad_added(move |demux, src_pad| { let templateName = get_property_name_template(&amp;src_pad); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope </code></pre> <p>a more manual way is to get the name then if else, but is there a more direct method?</p> <pre><code>println!( "Received new pad {}", src_pad.get_name() ); </code></pre> <p>I have also tried matching the pad form a template</p> <pre><code>.connect_pad_created('video_%u', src_pad{ .... </code></pre> <p>but I could not find a way to match the string of the template.</p>
How to format types implementing Display in rust?
<p>playground link: <a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=ed531c76be5298b858a05c705292a804" rel="nofollow noreferrer">https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=ed531c76be5298b858a05c705292a804</a></p> <p>How can I format structs that implement the Display trait?<br /> Seems a bit redundant to need to call to_string() on everything?</p> <pre><code>struct MyStruct(); impl std::fmt::Display for MyStruct { fn fmt(&amp;self, f: &amp;mut std::fmt::Formatter&lt;'_&gt;) -&gt; std::fmt::Result { write!(f, &quot;X&quot;) } } fn main() { let x = MyStruct{}; let y = &quot;Y&quot;; println!(&quot;{:_^9}&quot;, x); // WHY isnt this properly formatted? println!(&quot;{:_^9}&quot;, x.to_string()); println!(&quot;{:_^9}&quot;, y); } </code></pre> <p>outputs:</p> <pre><code>X ____X____ ____Y____ </code></pre> <p>What am I doing wrong?</p>
Is there a word for languages "equivalent to C"?
<p>I'm trying to find a word to categorize some languages, and don't quite have it.</p> <ul> <li>Category 1 Example: A Ruby program must be interpreted; it is really instructions for the <code>ruby</code> program. Python and Javascript are like this, too.</li> <li>Category 2 Example: A compiled C program needs no interpreter; it is really instructions for the computer. C++ , Rust and Go are like this, too.</li> </ul> <p>I would say "compiled vs interpreted", but there are languages that compile to bytecode. Eg, Java compiles, but you can't run a Java program without having Java installed.</p> <p>I would say "compiles to machine code", but I've read that C compilers may compile to assembler instead, and I'm fuzzy on that distinction anyway. Which raises the question "are we even talking about a feature of the language itself?" You can write <a href="https://code.google.com/p/picoc/" rel="nofollow">a C interpreter</a>, after all.</p> <p>Informally, I'd say "you can use Rust or Go to do the kinds of things you'd use C for - to produce efficient binaries with no runtime dependencies."</p> <p>Is there a word for "equivalent to C" in this sense?</p>
Function returning reference to self can't compile, while the same code can
<p>Given two snippets, which tries to return reference to a member value from self, I really can't understand why the one with separate function doesn't compile.</p> <p>This works (<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=58d1ba564e2a52fe2ac0eb395a363614" rel="nofollow noreferrer">godbolt</a>):</p> <pre class="lang-rust prettyprint-override"><code>struct Foo { a: bool, b: u32, } impl Foo { fn get(&amp;mut self) -&gt; &amp;u32 { if self.a { return &amp;self.b; } self.a = true; self.b = 10; return &amp;self.b; } } </code></pre> <p>While this doesn't (<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=18eb0c2fec5eac77227a90c245d7041e" rel="nofollow noreferrer">godbolt</a>):</p> <pre class="lang-rust prettyprint-override"><code>struct Foo { a: bool, b: u32, } impl Foo { fn try_get(&amp;self) -&gt; Option&lt;&amp;u32&gt; { if self.a { return Some(&amp;self.b); } return None; } fn get(&amp;mut self) -&gt; &amp;u32 { if let Some(val) = self.try_get() { return val; } self.a = true; self.b = 10; return &amp;self.b; } } </code></pre> <p>Error:</p> <pre><code>error[E0506]: cannot assign to `self.a` because it is borrowed --&gt; src/lib.rs:19:9 | 14 | fn get(&amp;mut self) -&gt; &amp;u32 { | - let's call the lifetime of this reference `'1` 15 | if let Some(val) = self.try_get() { | -------------- borrow of `self.a` occurs here 16 | return val; | --- returning this value requires that `*self` is borrowed for `'1` ... 19 | self.a = true; | ^^^^^^^^^^^^^ assignment to borrowed `self.a` occurs here </code></pre> <p>As I understand, it can't see, that reference at the top will be released before mutable change, but why? It can prove it without the function, why can't it do it with?<br /> Is there any way to make function call work?<br /> For me this really looks like a bug</p>
Why does Rust emit 280 lines of assembly code to print "Hello, world"?
<p>A simple 3-line Hello, World program in Rust emits a 280 line assembly file in order to print two words. Meanwhile, <a href="https://gist.github.com/FiloSottile/7125822" rel="nofollow noreferrer">a pure assembly version of this program</a> only takes ~15 lines. Why is the Rust version so much longer?</p> <p>This is on Mac OS.</p> <p><strong><code>hello.rs</code></strong>:</p> <pre><code>fn main() { println!("hello world") } </code></pre> <p><strong><code>hello.s</code></strong> (generated by <code>rustc --emit=asm hello.rs</code>):</p> <pre><code> .section __TEXT,__text,regular,pure_instructions .macosx_version_min 10, 7 .private_extern __ZN3std2rt10lang_start17hb4e01c1e588bf694E .globl __ZN3std2rt10lang_start17hb4e01c1e588bf694E .p2align 4, 0x90 __ZN3std2rt10lang_start17hb4e01c1e588bf694E: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset %rbp, -16 movq %rsp, %rbp .cfi_def_cfa_register %rbp subq $32, %rsp leaq l___unnamed_1(%rip), %rax movq %rdi, -8(%rbp) leaq -8(%rbp), %rcx movq %rcx, %rdi movq %rsi, -16(%rbp) movq %rax, %rsi movq -16(%rbp), %rax movq %rdx, -24(%rbp) movq %rax, %rdx movq -24(%rbp), %rcx callq __ZN3std2rt19lang_start_internal17hcf96e32a124891dcE movq %rax, -32(%rbp) movq -32(%rbp), %rax addq $32, %rsp popq %rbp retq .cfi_endproc .p2align 4, 0x90 __ZN3std2rt10lang_start28_$u7b$$u7b$closure$u7d$$u7d$17h275cd8632ff3ab7dE: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset %rbp, -16 movq %rsp, %rbp .cfi_def_cfa_register %rbp subq $16, %rsp callq *(%rdi) callq __ZN54_$LT$$LP$$RP$$u20$as$u20$std..process..Termination$GT$6report17hf5e270b394827df3E movl %eax, -4(%rbp) movl -4(%rbp), %eax addq $16, %rsp popq %rbp retq .cfi_endproc .p2align 4, 0x90 __ZN3std3sys4unix7process14process_common8ExitCode6as_i3217h7e671b2505e0c229E: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset %rbp, -16 movq %rsp, %rbp .cfi_def_cfa_register %rbp movzbl (%rdi), %eax popq %rbp retq .cfi_endproc .p2align 4, 0x90 __ZN4core3fmt9Arguments6new_v117h39ef65f250941772E: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset %rbp, -16 movq %rsp, %rbp .cfi_def_cfa_register %rbp subq $16, %rsp movq %rdi, %rax movq $0, -16(%rbp) movq %rsi, (%rdi) movq %rdx, 8(%rdi) movq -16(%rbp), %rdx movq -8(%rbp), %rsi movq %rdx, 16(%rdi) movq %rsi, 24(%rdi) movq %rcx, 32(%rdi) movq %r8, 40(%rdi) addq $16, %rsp popq %rbp retq .cfi_endproc .p2align 4, 0x90 __ZN4core3ops8function6FnOnce40call_once$u7b$$u7b$vtable.shim$u7d$$u7d$17h61f8ee8d3fead017E: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset %rbp, -16 movq %rsp, %rbp .cfi_def_cfa_register %rbp subq $16, %rsp movq (%rdi), %rdi callq __ZN4core3ops8function6FnOnce9call_once17h47f538be1b10688dE movl %eax, -12(%rbp) movl -12(%rbp), %eax addq $16, %rsp popq %rbp retq .cfi_endproc .p2align 4, 0x90 __ZN4core3ops8function6FnOnce9call_once17h47f538be1b10688dE: Lfunc_begin0: .cfi_startproc .cfi_personality 155, _rust_eh_personality .cfi_lsda 16, Lexception0 pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset %rbp, -16 movq %rsp, %rbp .cfi_def_cfa_register %rbp subq $48, %rsp movq %rdi, -32(%rbp) Ltmp0: leaq -32(%rbp), %rdi callq __ZN3std2rt10lang_start28_$u7b$$u7b$closure$u7d$$u7d$17h275cd8632ff3ab7dE Ltmp1: movl %eax, -36(%rbp) jmp LBB5_1 LBB5_1: jmp LBB5_2 LBB5_2: movl -36(%rbp), %eax addq $48, %rsp popq %rbp retq LBB5_3: jmp LBB5_4 LBB5_4: movq -16(%rbp), %rdi callq __Unwind_Resume ud2 LBB5_5: Ltmp2: movq %rax, -16(%rbp) movl %edx, -8(%rbp) jmp LBB5_3 Lfunc_end0: .cfi_endproc .section __TEXT,__gcc_except_tab .p2align 2 GCC_except_table5: Lexception0: .byte 255 .byte 255 .byte 1 .uleb128 Lcst_end0-Lcst_begin0 Lcst_begin0: .uleb128 Ltmp0-Lfunc_begin0 .uleb128 Ltmp1-Ltmp0 .uleb128 Ltmp2-Lfunc_begin0 .byte 0 .uleb128 Ltmp1-Lfunc_begin0 .uleb128 Lfunc_end0-Ltmp1 .byte 0 .byte 0 Lcst_end0: .p2align 2 .section __TEXT,__text,regular,pure_instructions .p2align 4, 0x90 __ZN4core3ptr18real_drop_in_place17h0ab16307507408dbE: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset %rbp, -16 movq %rsp, %rbp .cfi_def_cfa_register %rbp popq %rbp retq .cfi_endproc .p2align 4, 0x90 __ZN54_$LT$$LP$$RP$$u20$as$u20$std..process..Termination$GT$6report17hf5e270b394827df3E: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset %rbp, -16 movq %rsp, %rbp .cfi_def_cfa_register %rbp subq $16, %rsp xorl %edi, %edi callq __ZN68_$LT$std..process..ExitCode$u20$as$u20$std..process..Termination$GT$6report17h03f2ed18f1614f97E movl %eax, -4(%rbp) movl -4(%rbp), %eax addq $16, %rsp popq %rbp retq .cfi_endproc .p2align 4, 0x90 __ZN68_$LT$std..process..ExitCode$u20$as$u20$std..process..Termination$GT$6report17h03f2ed18f1614f97E: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset %rbp, -16 movq %rsp, %rbp .cfi_def_cfa_register %rbp subq $16, %rsp movb %dil, -1(%rbp) leaq -1(%rbp), %rdi callq __ZN3std3sys4unix7process14process_common8ExitCode6as_i3217h7e671b2505e0c229E movl %eax, -8(%rbp) movl -8(%rbp), %eax addq $16, %rsp popq %rbp retq .cfi_endproc .p2align 4, 0x90 __ZN5hello4main17hef70db39c48df377E: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset %rbp, -16 movq %rsp, %rbp .cfi_def_cfa_register %rbp subq $48, %rsp leaq l___unnamed_2(%rip), %rax xorl %ecx, %ecx movl %ecx, %r8d leaq -48(%rbp), %rdi movq %rax, %rsi movl $1, %edx movl $8, %ecx callq __ZN4core3fmt9Arguments6new_v117h39ef65f250941772E leaq -48(%rbp), %rdi callq __ZN3std2io5stdio6_print17hd8f597a6d310dad5E addq $48, %rsp popq %rbp retq .cfi_endproc .globl _main .p2align 4, 0x90 _main: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset %rbp, -16 movq %rsp, %rbp .cfi_def_cfa_register %rbp subq $16, %rsp movslq %edi, %rax leaq __ZN5hello4main17hef70db39c48df377E(%rip), %rdi movq %rsi, -8(%rbp) movq %rax, %rsi movq -8(%rbp), %rdx callq __ZN3std2rt10lang_start17hb4e01c1e588bf694E addq $16, %rsp popq %rbp retq .cfi_endproc .section __DATA,__const .p2align 3 l___unnamed_1: .quad __ZN4core3ptr18real_drop_in_place17h0ab16307507408dbE .quad 8 .quad 8 .quad __ZN3std2rt10lang_start28_$u7b$$u7b$closure$u7d$$u7d$17h275cd8632ff3ab7dE .quad __ZN3std2rt10lang_start28_$u7b$$u7b$closure$u7d$$u7d$17h275cd8632ff3ab7dE .quad __ZN4core3ops8function6FnOnce40call_once$u7b$$u7b$vtable.shim$u7d$$u7d$17h61f8ee8d3fead017E .section __TEXT,__const l___unnamed_3: .ascii "hello world\n" .section __DATA,__const .p2align 3 l___unnamed_2: .quad l___unnamed_3 .asciz "\f\000\000\000\000\000\000" .subsections_via_symbols </code></pre>
Unexpected behavior from str_replace()
<p>I have two arrays. One with color names and the other with the RGB values.</p> <p>I am converting a color name to it's RGB value using <code>str_replace()</code> (then doing some other stuff with it). </p> <p>All of the colours work as expected, except <code>Pale Yellow</code>.</p> <pre><code>$colour = "Pale Yellow"; $RGBint = array('Red' ,'Burgundy','Rust' ,'Electric Orange','Pumpkin' ,'Melon' ,'Baby Pink' ,'Candy Floss Pink','Electric Pink','Yellow' ,'Pale Yellow','Golden' ,'Lime' ,'Kiwi' ,'Mint' ,'Dragonfly Green','Kelly Green','Fern' ,'Forest Green','Olive' ,'Teal' ,'Baby Blue' ,'Dragonfly Blue','Cornflower' ,'Medium Blue','Royal Blue','Electric Blue','Navy' ,'Lavender' ,'Lilac' ,'Purple' ,'Plum' ,'Dark Brown','Chocolate Brown','Light Brown','Copper' ,'Beige' ,'Linen' ,'Taupe' ,'Shimmer' ,'Silver' ,'Medium Grey','Charcoal' ,'Black', 'White' , 'Off White' , 'Neon Light Orange','Neon Orange','Neon Light Pink','Neon Dark Pink','Neon Yellow','Neon Green'); $ColourName = array("200,16,46","166,9,61","150,56,33","255,106,19" ,"255,141,109","255,181,73","245,222,218","245,155,187" ,"239,74,129" ,"253,218,36","250,224,83" ,"203,160,82","206,220,0","142,221,101","128,224,167","169,196,127" ,"0,132,61" ,"142,221,101","0,87,63" ,"103,130,58","39,153,137","171,202,233","189,214,230" ,"123,175,212","95,143,180" ,"0,51,160" ,"0,125,186" ,"20,27,77","149,149,210","144,99,205","51,0,114","140,71,153","99,81,61" ,"105,63,35" ,"134,109,75" ,"115,56,29","219,200,182","176,170,126","138,126,112","208,211,212","162,172,171","142,144,137","112,115,114","0,0,0","255,255,255","227,223,195","255,170,77" ,"255,143,108","255,95,162" ,"239,66,111" ,"224,231,33" ,"255,233,0"); $RGBvalue = str_replace($RGBint, $ColourName, $colour); die($RGBvalue); </code></pre> <p>Expected result:</p> <pre><code>250,224,83 </code></pre> <p>Actual result: </p> <pre><code>Pale 250,224,83 </code></pre> <p>I don't understand why it is picking up "Pale" in the result, this isn't the only two word color, and the others work fine.</p> <p>I can't see anything obvious as to why this is happening, What am I missing?</p>
gcc complaining about undefined reference when the reference really is defined
<p>I'm trying to build a program using Rust's build system which calls through to gcc to perform linking. The actual linker command it's using is this monster:</p> <pre><code>"cc" "-Wl,--as-needed" "-Wl,-z,noexecstack" "-m64" "-L" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.16u6js6g0l3k1ic6.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.1im38lueib99jsk0.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.1y16o1qfye96o7m0.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.1zeawhkbeobww1zn.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.2f0hry2t7c05ttdi.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.2jqywn86b2gsqohu.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.2m5v7dirmv8f2te8.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.3171x0bwu82dptu7.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.3327un9ffw56pxvo.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.3ayaeypdcro9d6yk.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.3cx7oljifvb206q7.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.3j3lkwpgdcki40xe.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.3rngp6bm2u2q5z0y.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.45nf4z58qqykpcpi.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.49a7n47po4ttqjl7.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.4w4n11m1e8fds2qd.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.4xq48u46a1pwiqn7.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.4yh8x2b62dcih00t.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.8xzrsc1ux72v29j.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.98g0d9x8aw3akpe.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.9elsx31vb4it187.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.c6lbtaiefvx3wya.rcgu.o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.kt25z0521ngsjub.rcgu.o" "-o" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077" "/home/shum/src/rust/malk-compiled/target/debug/deps/malk_compiled-bc1cbad2728a2077.crate.allocator.rcgu.o" "-Wl,--gc-sections" "-pie" "-Wl,-z,relro,-z,now" "-nodefaultlibs" "-L" "/home/shum/src/rust/malk-compiled/target/debug/deps" "-L" "/nix/store/7z3ly87dkri33jp19maqvkdnjv0h1m1z-llvm-5.0.1-lib/lib" "-L" "/nix/store/z2xnpl533a60xcw3mr2l58b0vaa6cbpf-llvm-5.0.1/lib" "-L" "/home/shum/src/rust/malk-compiled/target/debug/build/llvm-sys-40845203bbf3195b/out" "-L" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib" "-l" "ffi" "-Wl,-Bstatic" "/home/shum/src/rust/malk-compiled/target/debug/deps/libllvm_sys-afd0e40fe14e6732.rlib" "/home/shum/src/rust/malk-compiled/target/debug/deps/liblibc-aa4528b7e880ecd5.rlib" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd-6c1b973d3d0bbe04.rlib" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/libpanic_unwind-78c5d8bda65d9986.rlib" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/liballoc_jemalloc-a48412ac73370f74.rlib" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/libunwind-1d8fa13d955fcd38.rlib" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/liballoc_system-0f7e40be987b8a0e.rlib" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/liblibc-9279fa66ae3bbdf0.rlib" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/liballoc-5645a289c27985c1.rlib" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd_unicode-77550ee3b4648e92.rlib" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcore-7f17c84607abc32e.rlib" "/home/shum/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcompiler_builtins-c4234f5034e47b78.rlib" "-Wl,-Bdynamic" "-l" "rt" "-l" "dl" "-l" "tinfo" "-l" "pthread" "-l" "z" "-l" "m" "-l" "stdc++" "-l" "util" "-l" "util" "-l" "dl" "-l" "rt" "-l" "pthread" "-l" "pthread" "-l" "gcc_s" "-l" "c" "-l" "m" "-l" "rt" "-l" "pthread" "-l" "util" "-l" "util" </code></pre> <p>The important part is that it includes <code>-l ffi</code>. The problem is, it still can't find symbols from libffi:</p> <pre><code>/home/shum/src/rust/malk-compiled/target/debug/deps/libllvm_sys-afd0e40fe14e6732.rlib(ExternalFunctions.cpp.o): In function `ffiTypeFor(llvm::Type*)': (.text._ZL10ffiTypeForPN4llvm4TypeE+0x3a): undefined reference to `ffi_type_float' /home/shum/src/rust/malk-compiled/target/debug/deps/libllvm_sys-afd0e40fe14e6732.rlib(ExternalFunctions.cpp.o): In function `ffiTypeFor(llvm::Type*)': (.text._ZL10ffiTypeForPN4llvm4TypeE+0x43): undefined reference to `ffi_type_void' /home/shum/src/rust/malk-compiled/target/debug/deps/libllvm_sys-afd0e40fe14e6732.rlib(ExternalFunctions.cpp.o): In function `ffiTypeFor(llvm::Type*)': (.text._ZL10ffiTypeForPN4llvm4TypeE+0x53): undefined reference to `ffi_type_pointer' /home/shum/src/rust/malk-compiled/target/debug/deps/libllvm_sys-afd0e40fe14e6732.rlib(ExternalFunctions.cpp.o): In function `ffiTypeFor(llvm::Type*)': (.text._ZL10ffiTypeForPN4llvm4TypeE+0x63): undefined reference to `ffi_type_double' /home/shum/src/rust/malk-compiled/target/debug/deps/libllvm_sys-afd0e40fe14e6732.rlib(ExternalFunctions.cpp.o): In function `ffiTypeFor(llvm::Type*)': (.text._ZL10ffiTypeForPN4llvm4TypeE+0x78): undefined reference to `ffi_type_sint8' /home/shum/src/rust/malk-compiled/target/debug/deps/libllvm_sys-afd0e40fe14e6732.rlib(ExternalFunctions.cpp.o): In function `ffiTypeFor(llvm::Type*)': (.text._ZL10ffiTypeForPN4llvm4TypeE+0x83): undefined reference to `ffi_type_sint16' /home/shum/src/rust/malk-compiled/target/debug/deps/libllvm_sys-afd0e40fe14e6732.rlib(ExternalFunctions.cpp.o): In function `ffiTypeFor(llvm::Type*)': (.text._ZL10ffiTypeForPN4llvm4TypeE+0x93): undefined reference to `ffi_type_sint64' /home/shum/src/rust/malk-compiled/target/debug/deps/libllvm_sys-afd0e40fe14e6732.rlib(ExternalFunctions.cpp.o): In function `ffiTypeFor(llvm::Type*)': (.text._ZL10ffiTypeForPN4llvm4TypeE+0xb3): undefined reference to `ffi_type_sint32' /home/shum/src/rust/malk-compiled/target/debug/deps/libllvm_sys-afd0e40fe14e6732.rlib(ExternalFunctions.cpp.o): In function `llvm::Interpreter::callExternalFunction(llvm::Function*, llvm::ArrayRef&lt;llvm::GenericValue&gt;)': (.text._ZN4llvm11Interpreter20callExternalFunctionEPNS_8FunctionENS_8ArrayRefINS_12GenericValueEEE+0x7d7): undefined reference to `ffi_prep_cif' /home/shum/src/rust/malk-compiled/target/debug/deps/libllvm_sys-afd0e40fe14e6732.rlib(ExternalFunctions.cpp.o): In function `llvm::Interpreter::callExternalFunction(llvm::Function*, llvm::ArrayRef&lt;llvm::GenericValue&gt;)': (.text._ZN4llvm11Interpreter20callExternalFunctionEPNS_8FunctionENS_8ArrayRefINS_12GenericValueEEE+0x82d): undefined reference to `ffi_call' collect2: error: ld returned 1 exit status </code></pre> <p>This is weird since it's definitely finding libffi. I can confirm this by running the linking command through strace:</p> <pre><code>... 20840 openat(AT_FDCWD, "/nix/store/fxfghra58jcx92csjypysd4l84gnz5wn-clang-5.0.1-lib/lib/libffi.so", O_RDONLY) = -1 ENOENT (No such file or directory) 20840 openat(AT_FDCWD, "/nix/store/fxfghra58jcx92csjypysd4l84gnz5wn-clang-5.0.1-lib/lib/libffi.a", O_RDONLY) = -1 ENOENT (No such file or directory) 20840 openat(AT_FDCWD, "/nix/store/1rh13l22z3j08ikir2bl4v6mldf747l6-libffi-3.2.1-dev/lib/libffi.so", O_RDONLY) = -1 ENOENT (No such file or directory) 20840 openat(AT_FDCWD, "/nix/store/1rh13l22z3j08ikir2bl4v6mldf747l6-libffi-3.2.1-dev/lib/libffi.a", O_RDONLY) = -1 ENOENT (No such file or directory) 20840 openat(AT_FDCWD, "/nix/store/5mg32439k1lam17dwq9xyk52i4hcwlqy-libffi-3.2.1/lib/libffi.so", O_RDONLY) = 31 </code></pre> <p>I can also run <code>nm -D</code> on that file and confirm that it does indeed contain the missing symbols:</p> <pre><code>... 00000000000063d0 R ffi_type_double 00000000000063f0 R ffi_type_float 00000000000063b0 R ffi_type_longdouble 0000000000006410 R ffi_type_pointer ... </code></pre> <p>I can even see them being read-out in the strace log:</p> <pre><code>20840 read(31, "dlmmap.constprop.12\0open_temp_exec_file_mutex\0selinux_enabled\0emutramp_enabled\0classify_argument\0examine_argument\0__FRAME_END__\0ffi_prep_cif_core\0__dso_handle\0_DYNAMIC\0__GNU_EH_FRAME_HDR\0__TMC_END__\0_GLOBAL_OFFSET_TABLE_\0ffi_type_void\0getenv@@GLIBC_2.2.5\0ffi_type_double\0ffi_prep_closure_loc\0ffi_prep_cif\0free@@GLIBC_2.2.5\0ffi_type_complex_double\0endmntent@@GLIBC_2.2.5\0ffi_java_raw_to_ptrarray\0abort@@GLIBC_2.2.5\0__errno_location@@GLIBC_2.2.5\0unlink@@GLIBC_2.2.5\0_ITM_deregisterTMCloneTable\0ffi_type_sint8\0ffi_java_raw_call\0_edata\0fclose@@GLIBC_2.2.5\0ffi_prep_closure\0ffi_type_uint16\0_fini\0strlen@@GLIBC_2.2.5\0__stack_chk_fail@@GLIBC_2.4\0mmap@@GLIBC_2.2.5\0ffi_type_sint32\0getmntent_r@@GLIBC_2.2.5\0strchr@@GLIBC_2.2.5\0ftruncate@@GLIBC_2.2.5\0mkostemp@@GLIBC_2.7\0ffi_type_uint8\0ffi_type_float\0ffi_raw_to_ptrarray\0ffi_type_uint64\0ffi_type_sint64\0ffi_prep_raw_closure_loc\0__getdelim@@GLIBC_2.2.5\0ffi_type_pointer\0ffi_closure_unix64\0__gmon_start__\0memcpy@@GLIBC_2.14\0ffi_type_uint32\0ffi_type_sint16\0ffi_closure_unix64_inner\0statf"..., 4096) = 3576 </code></pre> <p>So how is this possible? How is it that gcc can see the correct library, is reading it, but still complains about undefined references?</p>
`cfg` which is always true / false?
<p>For testing purpose I need <code>cfg</code> which is always true / false. For true I use</p> <pre class="lang-rust prettyprint-override"><code>#[ cfg( target_pointer_width = &quot;64&quot;) ] ... </code></pre> <p>But obviously it is not general enough. What is optimal way of expressing <code>cfg</code> to get necessary value?</p>
Trying to modify a Vec of futures inside a Rc<RefCell<...>>
<p>I try to wait and remove one-by-one future from a <code>Vec</code> of futures. It does not work. I understand why it does not work: <code>Pin</code> is not copyable. But how to correct this error?</p> <pre class="lang-rust prettyprint-override"><code>extern crate futures; use std::cell::{RefCell}; use std::rc::Rc; use std::pin::Pin; use std::future::Future; use futures::channel::oneshot::Canceled; use futures::executor::block_on; use futures::future::select_all; fn run_queries_body() { let _futures: Vec&lt;Pin&lt;Box&lt;dyn Future&lt;Output=Result&lt;(), Canceled&gt;&gt;&gt;&gt;&gt; = Vec::new(); let futuresRc = Rc::new(RefCell::new(_futures)); // TODO: Cell instead // This in actual could be called inside another future, so we need Rc&lt;RefCell&lt;...&gt;&gt; let mut futures = futuresRc.borrow_mut(); let f3 = futures.iter().map(|x| *x); let (_res, _idx, remaining_futures) = block_on(select_all(f3)); *futures = remaining_futures; } </code></pre> <pre class="lang-none prettyprint-override"><code>error[E0507]: cannot move out of `*x` which is behind a shared reference --&gt; src/lib.rs:16:37 | 16 | let f3 = futures.iter().map(|x| *x); | ^^ move occurs because `*x` has type `std::pin::Pin&lt;std::boxed::Box&lt;dyn futures::Future&lt;Output = std::result::Result&lt;(), futures::channel::oneshot::Canceled&gt;&gt;&gt;&gt;`, which does not implement the `Copy` trait </code></pre>
Can a trait give default implementation for *some* methods of a parent trait?
<p>Suppose we have a basic trait and an advanced trait as follows:</p> <pre class="lang-rust prettyprint-override"><code>pub trait BasicTrait { fn key_method(&amp;self); fn other_method(&amp;self); } pub trait AdvancedTrait: BasicTrait { fn key_method_with_argument(&amp;self, parameter: u32); } </code></pre> <p>Now, every time someone will implement <code>AdvancedTrait</code>, the most likely implementation of <code>BasicTrait::key_method(&amp;self)</code> is calling <code>key_method_with_argument</code> with some default argument. How can I provide this default implementation (idiomatically) so that anyone implementing <code>AdvancedTrait</code> will (1) only need to implement <code>key_method_with_argument</code> and any other required methods from <code>BasicTrait</code>, and (2) <em>optionally</em> implement <code>key_method()</code> and override the default implementation, only if needed?</p> <p>Related questions:</p> <p>having an <code>impl</code> block as proposed in the answer <a href="https://stackoverflow.com/questions/52418809/can-a-trait-give-a-default-implementation-for-the-method-of-a-trait-that-it-inhe">here</a> does not work since the code is expected to implement all other methods of <code>BasicTrait</code>.</p>
Cannot get Hash::get_mut() and File::open() to agree about mutability
<p>During a lengthy computation, I need to look up some data in a number of different files. I cannot know beforehand how many or which files exactly, but chances are high that each file is used many times (on the order of 100 million times).</p> <p>In the first version, I opened the file (whose name is an intermediate result of the computation) each time for lookup.</p> <p>In the second version, I have a <code>HashMap&lt;String, Box&lt;File&gt;&gt;</code> where I remember already open files and open new ones lazily on demand.</p> <p>I couldn't manage to handle the mutable stuff that arises from the need to have <code>File</code>s to be mutable. I got something working, but it looks overly silly:</p> <pre class="lang-rust prettyprint-override"><code>let path = format!(&quot;egtb/{}.egtb&quot;, self.signature()); let hentry = hash.get_mut(&amp;self.signature()); let mut file = match hentry { Some(f) =&gt; f, None =&gt; { let rfile = File::open(&amp;path); let wtf = Box::new(match rfile { Err(ioe) =&gt; return Err(format!(&quot;could not open EGTB file {} ({})&quot;, path, ioe)), Ok(opened) =&gt; opened, }); hash.insert(self.signature(), wtf); // the following won't work // wtf // &amp;wtf // &amp;mut wtf // So I came up with the following, but it doesn't feel right, does it? hash.get_mut(&amp;self.signature()).unwrap() } }; </code></pre> <p>Is there a canonical way to get a <code>mut File</code> from <code>File::open()</code> or <code>File::create()</code>? In the manuals, this is always done with:</p> <pre><code>let mut file = File:open(&quot;foo.txt&quot;)?; </code></pre> <p>This means my function would have to return <code>Result&lt;_, io::Error&gt;</code> and I can't have that.</p> <p>The problem seems to be that with the hash-lookup <code>Some(f)</code> gives me a <code>&amp;mut File</code> but the <code>Ok(f)</code> from <code>File::open</code> gives me just a <code>File</code>, and I don't know how to make a mutable reference from that, so that the match arm's types match. I have no clear idea why the version as above at least compiles, but I'd very much like to learn how to do that without getting the <code>File</code> from the <code>HashMap</code> again.</p>
Returning Result<(), Box<dyn Error>> in rust
<p>I have a function in golang -</p> <pre class="lang-golang prettyprint-override"><code> func (s *Server) getEnforcer(handle int) (*casbin.Enforcer, error) { if _, ok := s.enforcerMap[handle]; ok { return s.enforcerMap[handle], nil } else { return nil, errors.New(&quot;enforcer not found&quot;) } } </code></pre> <p>I am trying to implement this in rust. I have written this -</p> <pre class="lang-rs prettyprint-override"><code>impl Server { fn getEnforcer(&amp;mut self, handle: i32) -&gt; Result&lt;Enforcer, Box&lt;dyn Error&gt;&gt; { let e: Enforcer = self.enforcerMap[&amp;handle]; // match .. } } </code></pre> <p>Can't figure out how to handle error.</p>
How to share a rust unpublished cdy lib into Buildroot and use it
<p>When you create a custom rust library package into buildroot 2021, and you want to use it into another rust app package, you have to specify its path into Cargo.toml. The problem is buildroot package build path changed according to your workspace, and the buildroot version of your package (In the Cargo.toml, you specify: libxxx = { path = &quot;../../libxxx-&quot;}). Is there a way to inform cargo how to resolve the libxx path without specifying this path ?</p>
How to avoid mutable and immutable borrow with IntoParallelIterator bound
<p>I have a function that operates on a <code>Vec&lt;T&gt;</code> which purpose is to extend the vector with new items generated using reference to existing items. I'm trying to run the generation of new data in parallel using <code>rayon</code>.</p> <p>This is a minimal example:</p> <pre class="lang-rust prettyprint-override"><code>use itertools::Itertools; use rayon::prelude::*; fn main() { let mut foo = Foo { data: (0..1000).into_iter().collect(), }; foo.run(); } struct Foo&lt;T&gt; { data: Vec&lt;T&gt;, } type Pair&lt;'a, T&gt; = (&amp;'a T, &amp;'a T); impl&lt;'a, T: Clone + 'a&gt; Foo&lt;T&gt; where Vec&lt;Pair&lt;'a, T&gt;&gt;: IntoParallelIterator&lt;Item = Pair&lt;'a, T&gt;&gt;, [T; 2]: IntoParallelIterator, Vec&lt;T&gt;: FromParallelIterator&lt;&lt;[T; 2] as IntoParallelIterator&gt;::Item&gt;, { fn run(&amp;'a mut self) { let combinations: Vec&lt;Pair&lt;'a, T&gt;&gt; = self .data .iter() .combinations(2) .map(|x| (x[0], x[1])) .collect(); let mut new_combinations: Vec&lt;T&gt; = combinations .into_par_iter() .flat_map(|(a, b)| bar(a, b)) .collect(); self.data.append(&amp;mut new_combinations); } } fn bar&lt;T: Clone&gt;(a: &amp;T, b: &amp;T) -&gt; [T; 2] { [a.clone(), b.clone()] } </code></pre> <p>You can find a link to Playground <a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=91f5b11f9469a2356853d4f84e7ee58c" rel="nofollow noreferrer">here</a>.</p> <p>Building the above example raises this error:</p> <pre><code>error[E0502]: cannot borrow `self.data` as mutable because it is also borrowed as immutable --&gt; src/main.rs:36:9 | 17 | impl&lt;'a, T: Clone + 'a&gt; Foo&lt;T&gt; | -- lifetime `'a` defined here ... 24 | let combinations: Vec&lt;Pair&lt;'a, T&gt;&gt; = self | ___________________________----------------___- | | | | | type annotation requires that `self.data` is borrowed for `'a` 25 | | .data 26 | | .iter() | |___________________- immutable borrow occurs here ... 36 | self.data.append(&amp;mut new_combinations); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here </code></pre> <p>As far as I understand since I am collecting into a <code>let new_combinations: Vec&lt;T&gt;</code> there should be no immutable references to <code>self.data</code> and I should be able in theory to borrow it mutably to append the new combinations. However, it seems that <code>self.data</code> is borrowed for <code>'a</code> which extends beyond the scope of this method. I cannot find a way to avoid specifying the lifetime <code>fn run(&amp;'a mut self)</code> since I need to specify that the lifetimes of the references to the items of <code>self.data</code> cannot outlive <code>self</code> when creating the combinations.</p> <p>Is there a way to allow this method to operate as expected, that is: 1) select a list of references to the items in <code>self.data</code>, 2) apply a function that creates new items <code>T</code> in parallel and finally 3) update <code>self.data</code> with the new items.</p> <p>Note that as a workaround one could return the <code>new_combinations</code> from the method and append them to <code>self.data</code> separately.</p> <p>Would be great if all of this would be possible by avoiding as many <code>collect()</code> as possible while operating directly with iterators only.</p>
Why does my parallel merge algorithm produce the correct values in all positions of the output except the first?
<p>I am writing a parallel merging algorithm in Rust using <code>scoped-threadpool</code>, but it seems to be producing the correct values in all positions of the output except the first.</p> <p>I am attempting to adapt the pseudocode from the merge algorithm <a href="https://en.wikipedia.org/wiki/Merge_algorithm#Parallel_merge" rel="nofollow noreferrer">Wikipedia page</a>:</p> <pre><code>fn parallel_merge(first: &amp;[i32], second: &amp;[i32], output: &amp;mut [i32]) { let mut n = first.len(); let mut m = second.len(); let a; let b; // Make sure that 'first' is the largest of the two to be merged if m &lt; n { a = first; b = second; } else { a = second; b = first; let tmp = n; n = m; m = tmp; } if m &lt;= 0 { return; } let pivot = n / 2; let s = bisect(a[pivot], b); let t = pivot + s; output[t] = a[pivot]; let mut pool = Pool::new(2); pool.scoped(|scoped| { let (left, right) = output.split_at_mut(t); scoped.execute(move || { parallel_merge(&amp;a[..pivot], &amp;b[..s], left); }); scoped.execute(move || { parallel_merge(&amp;a[pivot..], &amp;b[s..], right); }); }); } </code></pre> <p>When called with <code>first</code> as the slice <code>[1, 3, 5, 7, 9]</code>, <code>second</code> as <code>[2, 4, 6, 8, 10]</code> and a slice of ten zeroes as the initial output, <code>output</code> is left as <code>[0, 2, 3, 4, 5, 6, 7, 8, 9]</code>.</p> <p>What is going wrong? As far as I can see, it matches the pseudocode aside from the unnecessary tracking of indexes.</p>
How to use use Pin rather than Arc to pass a Vec<u8> by reference to an async block?
<p>I want to do an operation on a <code>Vec&lt;u8&gt;</code> multiple times using an <code>Arc</code>:</p> <pre><code>use futures::{ executor::{block_on, ThreadPool}, task::SpawnExt, }; // 0.3.4 use std::{pin::*, sync::Arc}; fn foo(b: Arc&lt;Vec&lt;u8&gt;&gt;) { println!("{:?}", b); } #[test] fn pin_test() { let v = Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); let mut pool = ThreadPool::new().unwrap(); for _ in 0..10 { let v1 = v.clone(); let handle = pool .spawn_with_handle(async { foo(v1); }) .unwrap(); block_on(handle); } } </code></pre> <p>I was expecting to be able to <code>Pin</code> the <code>Vec&lt;u8&gt;</code> instead</p> <pre><code>use futures::{ executor::{block_on, ThreadPool}, task::SpawnExt, }; // 0.3.4 use std::{pin::*, sync::Arc}; fn foo(b: &amp;[u8]) { println!("{:?}", b); } #[test] fn pin_test() { let v = Pin::new(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); let mut pool = ThreadPool::new().unwrap(); for _ in 0..10 { let v1 = v.clone(); let handle = pool .spawn_with_handle(async { foo(&amp;*v1); }) .unwrap(); block_on(handle); } } </code></pre> <p>This gives the error:</p> <pre class="lang-none prettyprint-override"><code>error[E0597]: `v1` does not live long enough --&gt; src/lib.rs:19:23 | 18 | .spawn_with_handle(async { | ________________________________-_____- | |________________________________| | || 19 | || foo(&amp;*v1); | || ^^ borrowed value does not live long enough 20 | || }) | || - | ||_____________| | |______________value captured here by generator | argument requires that `v1` is borrowed for `'static` ... 23 | } | - `v1` dropped here while still borrowed </code></pre> <p>I understood that <code>Pin</code> should pin the <code>Vec</code> data to a specific point, such that all the calls could reference the same data. What is the right way to use <code>Pin</code> so that I can pass a reference to <code>foo()</code>?</p> <p>I'm using Rust 1.39.</p>
delwin does not delete the window
<p>I'm using Rust for my ncurses app.</p> <p>When the user presses F5, line numbers window should be toggled. When the user presses the F5 key for the first time, the window appears as it is supposed to. However, on second key press, the window does not go away, it's still there, as if the delwin call does not succeed. I tried refreshing the screen after it, but have had no success.</p> <p>Here's a minimal example:</p> <pre><code>use ncurses::*; struct LineNumbers { window: WINDOW, shown: bool } impl LineNumbers { fn new() -&gt; LineNumbers { LineNumbers { window: newwin(LINES(), 5, 0, 0), shown: false } } fn toggle(&amp;mut self) { if self.shown == true { self.hide(); } else { self.show(); } } fn show(&amp;mut self) { self.shown = true; wbkgd(self.window, COLOR_PAIR(1)); wrefresh(self.window); } fn hide(&amp;mut self) { self.shown = false; delwin(self.window); refresh(); } } fn main() { setlocale(LcCategory::all, ""); initscr(); keypad(stdscr(), true); start_color(); init_pair(1, COLOR_RED, COLOR_RED); let mut ln = LineNumbers::new(); loop { let user_input = get_wch(); match user_input.unwrap() { WchResult::Char(ch) =&gt; { match ch { 27 =&gt; break, _ =&gt; {} } }, WchResult::KeyCode(code) =&gt; { match code { KEY_F5 =&gt; { ln.toggle(); }, _ =&gt; {} } } } } endwin(); } </code></pre> <p>What could be the issue?</p>
Rust Notify (Filewatcher) is not debouncing events
<p>I am trying to create a filewatcher in rust using the notify-crate. Since I don't want it to spam all events but rather just tell once if a change occured I tried using a debounced filewatcher:</p> <pre><code>pub fn create_watcher(path: &amp;str) -&gt; Result&lt;(ReadDirectoryChangesWatcher, Receiver&lt;DebouncedEvent&gt;), notify::Error&gt; { let (sender, receiver) = channel(); // should debounce for 10s let mut watcher = watcher(sender, Duration::from_secs(10))?; watcher.watch(path, RecursiveMode::Recursive)?; Ok((watcher, receiver)) } </code></pre> <p>Yet it still creates an event for every operation it notices. The usage of the function can be seen below:</p> <pre><code>#[tauri::command] fn listen_installed(window: Window) { thread::spawn(move || { let username = env::var(&quot;USERNAME&quot;).unwrap(); let channel = create_watcher(&amp;format!(&quot;C:\\Users\\{}\\scoop\\apps&quot;, username)).unwrap(); loop { match channel.1.recv() { Ok(ok) =&gt; { window.emit(&quot;installed-packages-changed&quot;, None::&lt;&amp;str&gt;); }, Err(e) =&gt; println!(&quot;{:?}&quot;, &amp;e.to_string()), }; } }); } </code></pre> <p>Haven't I used the file-watcher properly or did I missunderstand what a &quot;Debounced-Watcher&quot; is?</p>
Convert String to Vec<char> at compile time for pattern matching
<p>I'm writing a parser in Rust and I'm creating tokens from a <code>Vec&lt;char&gt;</code>. Currently, my code looks like</p> <pre class="lang-rust prettyprint-override"><code>match &amp;source[..] { ['l', 'e', 't', ..] =&gt; ..., ['t', 'r', 'u', 'e', ..] =&gt; ..., _ =&gt; ... } </code></pre> <p>Obviously this is a lot more verbose than I'd like, and not easy to read. Is there any way I can convert <code>&quot;let&quot;</code> to <code>['l', 'e', 't']</code> at compile time (with a macro or const function) in order to pattern match on it like this?</p>
warn unused_doc_comments for macros
<p>How can I add and use doc comments with a macro invocation?</p> <pre><code>macro_rules! foo { ( $(#[$outer:meta])* $name:ident ) =&gt; { pub mod $name { $(#[$outer])* pub const THE_ANSWER: i32 = 42; } } } /// doc for macro created module foo!(bar); fn main() { println!(&quot;{}&quot;, bar::THE_ANSWER); } </code></pre> <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=36168f4e7650b3ef21a16f119d37c8bf" rel="nofollow noreferrer">Playground Link</a></p> <p>I seem to be doing what's recommended by <a href="https://stackoverflow.com/questions/33999341/generating-documentation-in-macros">this question</a> but I still get the warning.</p> <pre><code>warning: unused doc comment --&gt; src/main.rs:13:1 | 13 | /// doc for macro created module | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro invocations | = note: `#[warn(unused_doc_comments)]` on by default = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion </code></pre>
Calculate sum of chars in parallel
<p>I have an array of strings. I would like to count the total chars but using threads for parallelisation (the original problem is not this but is similar).</p> <pre class="lang-rust prettyprint-override"><code>use std::thread; pub fn frequency&lt;'a&gt;(input: &amp;'a [&amp;'a str], worker_count: usize) -&gt; usize { let handlers: Vec&lt;thread::JoinHandle&lt;usize&gt;&gt; = input .chunks(worker_count) .map(|chunk| thread::spawn(calculate(chunk))) .collect(); let hashes = handlers.into_iter().map(|handler| handler.join().unwrap()); let mut sum = 0; for h in hashes { sum += h } sum } fn calculate&lt;'a&gt;(input: &amp;'a [&amp;'a str]) -&gt; impl Fn() -&gt; usize + 'a { move || input.iter().map(|s| s.len()).sum() } </code></pre> <p>The compiler tells me this:</p> <pre class="lang-none prettyprint-override"><code>error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements --&gt; src/lib.rs:5:10 | 5 | .chunks(worker_count) | ^^^^^^ | note: first, the lifetime cannot outlive the lifetime 'a as defined on the function body at 3:18... --&gt; src/lib.rs:3:18 | 3 | pub fn frequency&lt;'a&gt;(input: &amp;'a [&amp;'a str], worker_count: usize) -&gt; usize { | ^^ note: ...so that reference does not outlive borrowed content --&gt; src/lib.rs:4:52 | 4 | let handlers: Vec&lt;thread::JoinHandle&lt;usize&gt;&gt; = input | ^^^^^ = note: but, the lifetime must be valid for the static lifetime... note: ...so that the type `impl std::ops::Fn&lt;()&gt;` will meet its required lifetime bounds --&gt; src/lib.rs:6:22 | 6 | .map(|chunk| thread::spawn(calculate(chunk))) | ^^^^^^^^^^^^^ </code></pre> <p>I've tried to remove all lifetimes, use different lifetimes for <code>str</code> and the slice, and explicitly invoke <code>calculate::&lt;'a&gt;</code> but none of those solutions compile.</p> <p>The input lifetime is the same everywhere: <code>frequency</code> declares <code>'a</code> that is used in <code>calculate</code>, so the closure is bound to <code>'a</code> because the captured variables live for <code>'a</code>.</p> <p>Where am I wrong?</p> <p>NB: I would like not to use <code>'static</code>.</p>
Writing getter/setter properties in Rust
<p>I'm writing a very simple getter/setting model that I would like to start using in Rust for simplicity reasons using <code>struct</code> and <code>impl</code>.</p> <pre><code>struct Person { firstName: String, lastName: String, } impl Person { fn get_first_name(&amp;mut self) -&gt; String { return self.firstName; } fn get_last_name(&amp;mut self) -&gt; String { return self.lastName; } fn set_first_name(&amp;mut self, x: String) { self.firstName = x; } fn set_last_name(&amp;mut self, x: String) { self.lastName = x; } fn default() -&gt; Person { Person {firstName: "".to_string(), lastName: "".to_string()} } } fn main() { let mut my_person : Person = Person{ ..Person::default() }; my_person.set_first_name("John".to_string()); my_person.set_last_name("Doe".to_string()); println!("{}", my_person.firstName); println!("{}", my_person.lastName); } </code></pre> <p>When I run this snippet I get the following error.</p> <pre><code>src\main.rs:7:53: 7:57 error: cannot move out of borrowed content [E0507] src\main.rs:7 fn get_first_name(&amp;mut self) -&gt; String { return self.firstName; } ^~~~ src\main.rs:8:53: 8:57 error: cannot move out of borrowed content [E0507] src\main.rs:8 fn get_last_name(&amp;mut self) -&gt; String { return self.lastName; } ^~~~ error: aborting due to 2 previous errors Could not compile `sandbox`. </code></pre> <p>Can someone point out the mistake to me since I'm very new to Rust?</p> <p>Tips on writing this snippet better would be accepted too. I'm always looking for easier/faster readability.</p>
Cannot infer type for type parameter T, when the type is explicitly specified in a struct definition
<p>I have a struct definition which includes, among other things, this field:</p> <pre class="lang-rust prettyprint-override"><code>pub struct Separated&lt;'a, I, T&gt; { ..., // other fields, separated: NonNull&lt;dyn 'a + Iterator&lt;Item = T&gt;&gt;, } </code></pre> <p>Shortly after, in its constructor, I attempt to initialize that field as a dangling pointer:</p> <pre class="lang-rust prettyprint-override"><code>let sep = Separated { ..., // other fields separated: NonNull::dangling(), }; </code></pre> <p>This, weirdly, produces this error:</p> <pre class="lang-none prettyprint-override"><code>error[E0282]: type annotations needed | 16 | separated: NonNull::dangling(), | ^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `T` </code></pre> <p>There's nothing mysterious about that field; its type is explicitly set in the struct definition. I do not understand why the type inferencer cannot infer an appropriate type to inject there.</p> <p>A minimal 20-line example producing this error can be found below and <a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=9f9aa45641c2029dc12ab6e5ae56e74c" rel="noreferrer">on the playground</a>:</p> <pre class="lang-rust prettyprint-override"><code>use std::pin::Pin; use std::ptr::NonNull; pub struct Separated&lt;'a, T&gt; { t: &amp;'a T, separated: NonNull&lt;dyn 'a + Iterator&lt;Item = T&gt;&gt;, } impl&lt;'a, T&gt; Separated&lt;'a, T&gt; where T: 'a + Copy + PartialEq, { fn new(t: &amp;'a T) -&gt; Pin&lt;Box&lt;Self&gt;&gt; { let sep = Separated { t, separated: NonNull::dangling(), }; unimplemented!() } } </code></pre> <p>I do need <code>separated</code> to be a pointer to a trait object instead of a monomorphized type: the real trait object which it will contain is composed of a bunch of iterator combinators, including ones like <code>Map</code> and <code>TakeWhile</code>, whose types include function pointers and are therefore unnameable. </p> <p><code>NonNull::dangling</code> is not a parametric function: the <code>NonNull&lt;T&gt;</code> struct is parametric, but this function is not. Therefore, I can't just turbofish my way out of this. I'm not sure how I'd go about providing type annotations at all.</p> <hr> <p>Context, if useful: the whole reason I'm going down this path is I am attempting to create an iterator combinator, auto-implemented for all appropriate iterators, which injects a single element between each N elements of the origin iterator. It's not all that hard to accomplish for a single iterator, but much harder to do as a generic combinator, because the <code>IntoChunks</code> struct produced by Itertools' <code>chunks()</code> combinator is not itself an iterator, just a struct implementing <code>IntoIterator</code>. Therefore, we need to keep track of the <code>IntoChunks</code> struct as well as the iterator it produces. </p> <p>The approach I'm taking is to create a self-referential struct, <code>Separated</code>, which contains both of those. This should be safe assuming the struct is always pinned. I then <code>impl Iterator for Separated</code> and just defer the <code>next</code> calls to <code>self.separated</code>. </p>
Implement graph-like data structure in Rust
<p>I have a data structure which can be represented as a unidirectional graph between some structs linked with link objects because links contain metadata.</p> <p>It looks something like this:</p> <pre><code>struct StateMachine { resources: Vec&lt;Resource&gt;, links: Vec&lt;Link&gt;, } struct Resource { kind: ResourceType, // ... } enum LinkTarget { ResourceList(Vec&lt;&amp;Resource&gt;), LabelSelector(HashMap&lt;String, String&gt;), } struct Link { from: LinkTarget, to: LinkTarget, metadata: SomeMetadataStruct, } </code></pre> <p>The whole structure needs to be mutable because I need to be able to add and remove links and resources at runtime. Because of this, I cannot use the normal lifetime model and bind the resources to the parent struct's lifetime.</p> <p>I understand that I need <a href="https://doc.rust-lang.org/book/first-edition/choosing-your-guarantees.html" rel="noreferrer">to "choose my own guarantee"</a> by picking the appropriate type, but I'm not sure what's the best way to solve this problem.</p>
Building a cross-platform application (using Rust)
<p>I started to learn Rust programming language and I use Linux. I'd like to build a cross-platform application using this language. </p> <p>The question might not be related to Rust language in particular, but nonetheless, how do I do that? I'm interested in building a "Hello World" cross-platform application as well as for more complicated ones. I just need to get the idea.</p> <p>So what do I do?</p> <p><strong>UPDATE</strong>:</p> <p>What I want to do is the ability to run a program on 3 different platforms without changing the <strong>sources</strong>. Do I have to build a new binary file for each platform from the sources? Just like I could do in C</p>
How to do a binary search on a Vec of floats?
<p>If you have a <code>Vec&lt;u32&gt;</code> you would use the <a href="http://doc.rust-lang.org/std/primitive.slice.html#method.binary_search" rel="noreferrer"><code>slice::binary_search</code></a> method.</p> <p>For reasons I don't understand, <code>f32</code> and <code>f64</code> do not implement <code>Ord</code>. Since the primitive types are from the standard library, you cannot implement <code>Ord</code> on them yourself, so it does not appear you can use this method.</p> <p>How can you effectively do this? </p> <p>Do I really have to wrap <code>f64</code> in a wrapper struct and implement <code>Ord</code> on it? It seems extremely painful to have to do this, and involves a great deal of <code>transmute</code> to cast blocks of data back and forth unsafely for effectively no reason.</p>
Convert vectors to arrays and back
<p>I am attempting to figure the most Rust-like way of converting from a vector to array and back. These macros will work and can even be made generic with some unsafe blocks, but it all feels very un-Rust like.</p> <p>I would appreciate any input and hold no punches, I think this code is far from nice or optimal. I have only played with Rust for a few weeks now and chasing releases and docs so really appreciate help.</p> <pre><code>macro_rules! convert_u8vec_to_array { ($container:ident, $size:expr) =&gt; {{ if $container.len() != $size { None } else { use std::mem; let mut arr : [_; $size] = unsafe { mem::uninitialized() }; for element in $container.into_iter().enumerate() { let old_val = mem::replace(&amp;mut arr[element.0],element.1); unsafe { mem::forget(old_val) }; } Some(arr) } }}; } fn array_to_vec(arr: &amp;[u8]) -&gt; Vec&lt;u8&gt; { let mut vector = Vec::new(); for i in arr.iter() { vector.push(*i); } vector } fn vector_as_u8_4_array(vector: Vec&lt;u8&gt;) -&gt; [u8;4] { let mut arr = [0u8;4]; for i in (0..4) { arr[i] = vector[i]; } arr } </code></pre>
How do you copy between arrays of different sizes in Rust?
<p>If I have two arrays of different sizes:</p> <pre><code>let mut array1 = [0; 8]; let array2 = [1, 2, 3, 4]; </code></pre> <p>How would I copy <code>array2</code> into the first 4 bytes of <code>array1</code>? I can take a mutable 4 byte slice of array1, but I'm not sure how or if I can assign into it.</p>
How do I convert a HashSet of Strings into a Vector?
<p>I'm trying to convert a <code>HashSet&lt;String&gt;</code> into a sorted vector that can then be <code>join</code>ed with commas:</p> <pre><code>use std::collections::HashSet; fn main() { let mut hs = HashSet::&lt;String&gt;::new(); hs.insert(String::from("fee")); hs.insert(String::from("fie")); hs.insert(String::from("foo")); hs.insert(String::from("fum")); let mut v: Vec&lt;&amp;String&gt; = hs.iter().collect(); v.sort(); println!("{}", v.join(", ")); } </code></pre> <p>This will not compile:</p> <pre class="lang-none prettyprint-override"><code>error[E0599]: no method named `join` found for struct `std::vec::Vec&lt;&amp;std::string::String&gt;` in the current scope --&gt; src/main.rs:13:22 | 13 | println!("{}", v.join(", ")); | ^^^^ method not found in `std::vec::Vec&lt;&amp;std::string::String&gt;` </code></pre> <p>I understand why I can't join the <code>Vec&lt;&amp;String&gt;</code>, but how can I convert the <code>HashSet</code> to a <code>Vec&lt;String&gt;</code> instead, so it can be joined?</p> <p>The examples given in <a href="https://stackoverflow.com/q/36941851/96233">What&#39;s an idiomatic way to print an iterator separated by spaces in Rust?</a> do not seem to apply because the iterator for <code>Args</code> returns <code>String</code> values, unlike the iterator for <code>HashSet</code> which returns <code>&amp;String</code>.</p>
How to concatenate a char onto a string in Rust?
<p>I have tried using the <code>to_string</code> method on the char but this returns a <code>&amp;str</code> when I need a <code>String</code>.</p>
How to create a tuple from a vector?
<p>Here's an example that splits a string and parses each item, putting it into a tuple whose size is known at compile time.</p> <pre><code>use std::str::FromStr; fn main() { let some_str = "123,321,312"; let num_pair_str = some_str.split(',').collect::&lt;Vec&lt;&amp;str&gt;&gt;(); 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 number"), ); println!("Tuple {:?}", num_pair); } } </code></pre> <p>Is there a way to avoid repetition parsing the numbers? </p> <p>This is an example of what it might look like if Rust supported Python-like comprehensions:</p> <pre><code>let num_pair: (i32, i32, i32) = ( i32::from_str(num_pair_str[i]).expect("failed to parse number") for i in 0..3 ); </code></pre> <p>Is it possible to declare the tuple in a way that expands the vector?</p>
How to move tests into a separate file for binaries in Rust's Cargo?
<p>I created a new binary using Cargo:</p> <pre><code>cargo new my_binary --bin </code></pre> <p>A function in <code>my_binary/src/main.rs</code> can be used for a test:</p> <pre><code>fn function_from_main() { println!("Test OK"); } #[test] fn my_test() { function_from_main(); } </code></pre> <p>And <code>cargo test -- --nocapture</code> runs the test as expected.</p> <p>What's the most straightforward way to move this test into a separate file, (keeping <code>function_from_main</code> in <code>my_binary/src/main.rs</code>)?</p> <p>I tried to do this but am not sure how to make <code>my_test</code> call <code>function_from_main</code> from a separate file.</p>
How can I sort the characters of a string in Rust?
<p>I have the string "laxmi" and I need to sort it in descending alphabetical order, producing "xmlia". I have written this:</p> <pre><code>fn main() { let wordy: String = "I am a hello world example"; let chars: Vec&lt;char&gt; = wordy.chars().vector(); chars.sort_by(|a, b| b.cmp(a)); // let s: String = chars.into_iter().collect(); println!("test{:?}", chars); let s = String::from_iter(chars); println!("{}", s); } </code></pre> <p>This only works if <code>wordy</code> is a <code>&amp;str</code>, but I have a <code>String</code>. How can I convert the <code>String</code> to a vector of <code>char</code> so that I can sort the string?</p>
How do I specify lifetime parameters in an associated type?
<p>I have this trait and simple structure:</p> <pre><code>use std::path::{Path, PathBuf}; trait Foo { type Item: AsRef&lt;Path&gt;; type Iter: Iterator&lt;Item = Self::Item&gt;; fn get(&amp;self) -&gt; Self::Iter; } struct Bar { v: Vec&lt;PathBuf&gt;, } </code></pre> <p>I would like to implement the <code>Foo</code> trait for <code>Bar</code>:</p> <pre><code>impl Foo for Bar { type Item = PathBuf; type Iter = std::slice::Iter&lt;PathBuf&gt;; fn get(&amp;self) -&gt; Self::Iter { self.v.iter() } } </code></pre> <p>However I'm getting this error:</p> <pre class="lang-none prettyprint-override"><code>error[E0106]: missing lifetime specifier --&gt; src/main.rs:16:17 | 16 | type Iter = std::slice::Iter&lt;PathBuf&gt;; | ^^^^^^^^^^^^^^^^^^^^^^^^^ expected lifetime parameter </code></pre> <p>I found no way to specify lifetimes inside that associated type. In particular I want to express that the iterator cannot outlive the <code>self</code> lifetime.</p> <p>How do I have to modify the <code>Foo</code> trait, or the <code>Bar</code> trait implementation, to make this work?</p> <p><a href="https://play.rust-lang.org/?gist=b67ee336bf04f71d175a2bab2370d7cf&amp;version=stable&amp;backtrace=0" rel="noreferrer">Rust playground</a></p>
Cannot return a vector slice - ops::Range<i32> is not implemented
<p>Why does the following Rust code give an error?</p> <pre><code>fn getVecSlice(vec: &amp;Vec&lt;f64&gt;, start: i32, len: i32) -&gt; &amp;[f64] { vec[start..start + len] } </code></pre> <p>The error message I get is</p> <pre class="lang-none prettyprint-override"><code>the trait `core::ops::Index&lt;core::ops::Range&lt;i32&gt;&gt;` is not implemented for the type `collections::vec::Vec&lt;f64&gt;` [E0277] </code></pre> <p>In later versions of Rust, I get</p> <pre class="lang-none prettyprint-override"><code>error[E0277]: the trait bound `std::ops::Range&lt;i32&gt;: std::slice::SliceIndex&lt;[f64]&gt;` is not satisfied --&gt; src/main.rs:2:9 | 2 | vec[start..start + len] | ^^^^^^^^^^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize` | = help: the trait `std::slice::SliceIndex&lt;[f64]&gt;` is not implemented for `std::ops::Range&lt;i32&gt;` = note: required because of the requirements on the impl of `std::ops::Index&lt;std::ops::Range&lt;i32&gt;&gt;` for `std::vec::Vec&lt;f64&gt;` </code></pre> <p>I'm trying to simulate a 2 dimensional matrix using the <code>Vec</code> type and return references to the different rows of the matrix.What is the best way to achieve this?</p>
"exec format error" when running containers build with Apple M1 Chip (ARM based systems)
<p>Expected behavior: I can run a container I've built using an Apple M1 chip.</p> <p>Observed behavior:</p> <p>Assuming you have a Google Cloud Run account and can push Docker images to Google Container Registry. I'm using <a href="https://github.com/seenickcode/trivial-go-api" rel="noreferrer">https://github.com/seenickcode/trivial-go-api</a> for this example.</p> <ol> <li>`git clone git@github.com:seenickcode/trivial-go-api.git'</li> <li><code>cd trivial-go-api</code></li> <li><code>docker build -t gcr.io/&lt;YOUR GCR PROJECT ID&gt;/example .</code></li> <li><code>docker push -t gcr.io/&lt;YOUR GCR PROJECT ID&gt;/example</code></li> <li>Go to <code>console.cloud.google.com</code>, Google Cloud Run &gt; Create new service &gt; select your pushed Docker image with all default options &gt; Run</li> <li>Error shown:</li> </ol> <pre><code>Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information. </code></pre> <p>Logs:</p> <pre><code>2021-04-02 09:35:40.045 EDT Cloud Run ReplaceService example hello@redactedforso.com {@type: type.googleapis.com/google.cloud.audit.AuditLog, authenticationInfo: {…}, authorizationInfo: […], methodName: google.cloud.run.v1.Services.ReplaceService, request: {…}, requestMetadata: {…}, resourceLocation: {…}, resourceName: namespaces/myprojectforso-282419/services/example, response: {…}, servi… Error 2021-04-02 09:35:49.034 EDT terminated: Application failed to start: Failed to create init process: failed to load /app/main: exec format error Warning 2021-04-02 09:35:49.174 EDT Application exec likely failed Notice 2021-04-02 09:57:43.102 EDT Cloud Run ReplaceService example hello@redactedforso.com {@type: type.googleapis.com/google.cloud.audit.AuditLog, authenticationInfo: {…}, authorizationInfo: […], methodName: google.cloud.run.v1.Services.ReplaceService, request: {…}, requestMetadata: {…}, resourceLocation: {…}, resourceName: namespaces/myprojectforso-282419/services/example, response: {…}, servi… Error 2021-04-02 09:57:50.657 EDT terminated: Application failed to start: Failed to create init process: failed to load /app/main: exec format error </code></pre> <p>System details on where I'm building my image:</p> <ul> <li>OS: macOS 11.2.3</li> <li>Chip: Apple M1</li> <li>Docker version: Docker Desktop for macOS v3.3.0 (62345)</li> </ul> <p>Important Notes:</p> <ul> <li>This all works completely fine for me when I use another architecture, i.e. via Google Container Build or my home Windows (WSL) desktop.</li> <li>This also doesn't work with other codebases when built using the Apple M1 Chip, such as another project I have written in Rust as well as Dart. Doesn't seem language related.</li> <li>I've been using Google Cloud Run for years, this issue cropped up when using my new laptop with Apple M1 Chip.</li> </ul>
pkg-config error during Rust cross-compilation
<p>I am getting this error when I try to cross-compile some Rust; does anyone know what I should be doing?</p> <p>This happens when I run cargo build --target aarch64, I get:</p> <pre><code>Compiling glib-sys v0.10.1 error: failed to run custom build command for `glib-sys v0.10.1` ... pkg-config has not been configured to support cross-compilation. Install a sysroot for the target platform and configure it via PKG_CONFIG_SYSROOT_DIR and PKG_CONFIG_PATH, or install a cross-compiling wrapper for pkg-config and set it via PKG_CONFIG environment variable. </code></pre> <p>I might have asked this before a year or so ago, but anyway I cannot find any answer. I have tried adding various lines to my Cargo.toml but nothing seems to help.</p> <p>The relevant part of Cargo.toml has:</p> <pre><code>[target.'cfg(target_os = &quot;android&quot;)'.dependencies] cairo = &quot;0.0.4&quot; freetype = &quot;0.7.0&quot; glib = &quot;0.14.2&quot; openssl = &quot;0.10.36&quot; openssl-sys = {version = &quot;0.9.66&quot;, features = [&quot;vendored&quot;]} </code></pre> <p>There is probably a one-line answer to this; can anyone help me please.</p>
How can I invoke an unknown Rust function with some arguments using reflection?
<p>I'm having a lot of fun playing around with Rust having been a C# programmer for a long time but I have a question around reflection. Maybe I don't need reflection in this case but given that Rust is strongly typed I suspect I do (I would definitely need it in good ol' C#, bless its cotton socks).</p> <p>I have this situation:</p> <pre><code>use std::collections::HashMap; fn invoke_an_unknown_function( hashmap: HashMap&lt;String, String&gt;, // Something to denote a function I know nothing about goes here ) { // For each key in the hash map, assign the value // to the parameter argument whose name is the key // and then invoke the function } </code></pre> <p>How would I do that? I'm guessing I need to pass in some sort of <code>MethodInfo</code> as the second argument to the function and then poke around with that to get the arguments whose name is the key in the hash map and assign the values but I had a look around for the reflection API and found the following pre-Rust 1.0 documentation:</p> <ul> <li><a href="http://static.rust-lang.org/doc/0.8/std/reflect/index.html" rel="nofollow noreferrer">Module <code>std::reflect</code></a></li> <li><a href="http://static.rust-lang.org/doc/0.8/std/repr/index.html" rel="nofollow noreferrer">Module <code>std::repr</code></a></li> <li><a href="https://mail.mozilla.org/pipermail/rust-dev/2012-July/002064.html" rel="nofollow noreferrer">[rust-dev] Reflection system</a></li> </ul> <p>None of these give me enough to go on to get started. How would I implement the function I describe above?</p>
How do I use filter_map() rather then filter() combined with map() without performance decreasing?
<p>I would like to use <code>filter_map()</code> instead of <code>unwrap()</code> in the <code>map()</code> and <code>filter()</code> but I see a performance decrease when doing this. How do I write the code using <code>filter_map()</code> without losing performance? Why is there a loss of performance in the first place?</p> <p><strong>src/lib.rs</strong></p> <pre><code>use std::collections::HashMap; pub enum Kind { Square(Square), Circle(Circle), } #[derive(Default, Copy, Clone)] pub struct Circle { a: u32, b: u32, c: u32, d: u32, } #[derive(Default)] pub struct Square { a: u32, b: Option&lt;u32&gt;, c: Option&lt;u32&gt;, d: Option&lt;u32&gt;, e: Option&lt;u32&gt;, } impl Kind { pub fn get_circle(&amp;self) -&gt; Option&lt;&amp;Circle&gt; { if let Kind::Circle(b) = self { return Some(b); } None } } </code></pre> <p><strong>benches/test.rs</strong></p> <pre><code>#![feature(test)] extern crate test; #[cfg(test)] mod tests { use std::collections::HashMap; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use test::Bencher; use testing::Circle; use testing::Kind; use testing::Square; fn get_bencher() -&gt; HashMap&lt;SocketAddr, Kind&gt; { let mut question = HashMap::new(); let square: Square = Default::default(); question.insert( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0), Kind::Square(square), ); let circle: Circle = Default::default(); for n in 1..=10000 { let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), n); question.insert(socket, Kind::Circle(circle)); } question } #[bench] fn bencher01(b: &amp;mut Bencher) { let question = get_bencher(); b.iter(|| { question .iter() .map(|a| (a.0, a.1.get_circle())) .filter_map(|(&amp;a, b)| Some((a, b?))) .collect::&lt;Vec&lt;_&gt;&gt;() }) } #[bench] fn bencher02(b: &amp;mut Bencher) { let question = get_bencher(); b.iter(|| { question .iter() .map(|a| (a.0, a.1.get_circle())) .filter(|c| c.1.is_some()) .map(|d| (*d.0, d.1.unwrap())) .collect::&lt;Vec&lt;_&gt;&gt;() }) } #[bench] fn bencher03(b: &amp;mut Bencher) { let question = get_bencher(); b.iter(|| { question .iter() .filter_map(|a| Some((*a.0, a.1.get_circle()?))) .collect::&lt;Vec&lt;_&gt;&gt;() }) } } </code></pre> <p>Run these tests using Rust nightly and <code>cargo bench</code> which forces release mode.</p> <p><strong>output</strong></p> <pre class="lang-none prettyprint-override"><code>running 3 tests test tests::bencher01 ... bench: 201,978 ns/iter (+/- 12,787) test tests::bencher02 ... bench: 89,004 ns/iter (+/- 6,204) test tests::bencher03 ... bench: 238,569 ns/iter (+/- 6,004) </code></pre> <p>I'm using <code>rustc 1.44.0-nightly (6dee5f112 2020-04-06)</code> on <code>Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz Linux #### 5.6.4-arch1-1 #1 SMP PREEMPT Mon, 13 Apr 2020 12:21:19 +0000 x86_64 GNU/Linux</code></p>
Rust - sorry, unimplemented: 64-bit mode not compiled in
<p>When I <code>cargo run</code>, I get met with</p> <pre><code>error: failed to run custom build command for `ring v0.16.20` --- stderr running &quot;gcc.exe&quot; &quot;-O0&quot; &quot;-ffunction-sections&quot; &quot;-fdata-sections&quot; &quot;-g&quot; &quot;-fno-omit-frame-pointer&quot; &quot;-m64&quot; &quot;-I&quot; &quot;include&quot; &quot;-Wall&quot; &quot;-Wextra&quot; &quot;-std=c1x&quot; &quot;-Wbad-function-cast&quot; &quot;-Wnested-externs&quot; &quot;-Wstrict-prototypes&quot; &quot;-pedantic&quot; &quot;-pedantic-errors&quot; &quot;-Wall&quot; &quot;-Wextra&quot; &quot;-Wcast-align&quot; &quot;-Wcast-qual&quot; &quot;-Wconversion&quot; &quot;-Wenum-compare&quot; &quot;-Wfloat-equal&quot; &quot;-Wformat=2&quot; &quot;-Winline&quot; &quot;-Winvalid-pch&quot; &quot;-Wmissing-field-initializers&quot; &quot;-Wmissing-include-dirs&quot; &quot;-Wredundant-decls&quot; &quot;-Wshadow&quot; &quot;-Wsign-compare&quot; &quot;-Wsign-conversion&quot; &quot;-Wundef&quot; &quot;-Wuninitialized&quot; &quot;-Wwrite-strings&quot; &quot;-fno-strict-aliasing&quot; &quot;-fvisibility=hidden&quot; &quot;-g3&quot; &quot;-DNDEBUG&quot; &quot;-c&quot; &quot;-oC:\\Users\\Derpboimoon\\documents\\rust\\phosphorus\\target\\debug\\build\\ring-d6190243a10e7549\\out\\aes_nohw.o&quot; &quot;crypto/fipsmodule/aes/aes_nohw.c&quot; crypto/fipsmodule/aes/aes_nohw.c:1:0: sorry, unimplemented: 64-bit mode not compiled in /* Copyright (c) 2019, Google Inc. thread 'main' panicked at 'execution failed', C:\Users\Pat\.cargo\registry\src\github.com-1ecc6299db9ec823\ring-0.16.20\build.rs:656:9 </code></pre> <p>Here is my Cargo.toml file:</p> <pre><code>[package] name = &quot;phosphorus&quot; version = &quot;0.1.0&quot; edition = &quot;2018&quot; # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] tokio = { version = &quot;1.7.0&quot;, default-features = false, features = [&quot;macros&quot;, &quot;sync&quot;, &quot;rt-multi-thread&quot;] } twilight-http = &quot;0.3&quot; </code></pre> <p>I am using <code>rustup default stable-x86_64-pc-windows-gnu</code> if that helps.</p> <p>I read around stack overflow and it seems that I need to set the gcc target to x86_64. How do I do that? I suspect the error is from <code>tokio</code>, but not sure.</p> <p>Any help would be appreciated!</p>
Pass data for GET request using Hyper
<p>I am working on a Twitter API for Rust and am running into issues with passing arguments to my GET request. The code I'm using for the request is given below. <code>data_body</code> is something like "screen_name=a_user" and the authorization header is the OAuth authorization required by Twitter (this isn't the issue as it's working with all my other requests).</p> <pre><code>let mut res = client.get("http://httpbin.org/get") .body(&amp;data_body[..]) .header(Authorization(authorization_header)) .header(ContentType::form_url_encoded()) .send().unwrap(); </code></pre> <p>I started sending this to httpbin.org so I could see the raw request. What I'm getting back is shown below.</p> <pre><code>{ "args": {}, "headers": { "Authorization": "OAuth oauth_consumer_key=\"\", oauth_nonce=\"RH9vZYMCbAtfQAuVh44fhlyGQfQqBCPq\", oauth_signature=\"dTbOyaURct0auVlC%2B8Y7vDFpus0%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1452648640\", oauth_token=\"\", oauth_version=\"1.0\"", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org" }, "origin": "0.0.0.0", "url": "http://httpbin.org/get" } </code></pre> <p>The curl request given by the Twitter api docs have a data portion for the GET request below (I've replaced my keys with empty strings). I can confirm this works for the GET.</p> <pre><code>curl --get 'https://api.twitter.com/1.1/users/show.json' --data 'screen_name=twitterdev' --header 'Authorization: OAuth oauth_consumer_key="", oauth_nonce="6a37886cb38b2f5e12dee8fd47aa097c", oauth_signature="zhXDA5JbKRmw2xbJcEqK9sxuu5E%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1452647580", oauth_token="", oauth_version="1.0"' --verbose </code></pre> <p>I've tried a bunch of different <code>ContentType</code>s from the Hyper API but can't get the args section of the HTTP request populated. I think that's the issue, but I don't have a lot of experience with HTTP so I could very well be wrong. Ultimately the request is returning a 403 (Unauthorized) which is triggered by the missing args. I know my OAuth header is being generated correctly because it's working on all the POST requests and when I copy over the nonce and timestamp from the curl command I get from the Twitter API the signature matches.</p>
How can deserialization of polymorphic trait objects be added in Rust if at all?
<p>I'm trying to solve the problem of serializing and deserializing <code>Box&lt;SomeTrait&gt;</code>. I know that in the case of a closed type hierarchy, the recommended way is to use an enum and there are no issues with their serialization, but in my case using enums is an inappropriate solution.</p> <p>At first I tried to use Serde as it is the de-facto Rust serialization mechanism. Serde is capable of serializing <code>Box&lt;X&gt;</code> but not in the case when <code>X</code> is a trait. The <a href="https://docs.serde.rs/serde/trait.Serialize.html" rel="noreferrer"><code>Serialize</code></a> trait can’t be implemented for trait objects because it has generic methods. This particular issue can be solved by using <a href="https://github.com/dtolnay/erased-serde" rel="noreferrer">erased-serde</a> so serialization of <code>Box&lt;SomeTrait&gt;</code> can work.</p> <p>The main problem is deserialization. To deserialize polymorphic type you need to have some type marker in serialized data. This marker should be deserialized first and after that used to dynamically get the function that will return <code>Box&lt;SomeTrait&gt;</code>.</p> <p><code>std::any::TypeId</code> could be used as a marker type, but the main problem is how to dynamically get the deserialization function. I do not consider the option of registering a function for each polymorphic type that should be called manually during application initialization.</p> <p>I know two possible ways to do it:</p> <ol> <li>Languages that have runtime reflection like C# can use it to get deserialization method. </li> <li>In C++, the cereal library uses magic of static objects to register deserializer in a static map at the library initialization time.</li> </ol> <p>But neither of these options is available in Rust. How can deserialization of polymorphic objects be added in Rust if at all? </p>
How do I use the Entry API with an expensive key that is only constructed if the Entry is Vacant?
<p>Is it possible to use the <a href="https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html" rel="noreferrer"><code>Entry</code></a> API to get a value by a <code>AsRef&lt;str&gt;</code>, but inserting it with <code>Into&lt;String&gt;</code>?</p> <p>This is the working example:</p> <pre class="lang-rust prettyprint-override"><code>use std::collections::hash_map::{Entry, HashMap}; struct Foo; #[derive(Default)] struct Map { map: HashMap&lt;String, Foo&gt;, } impl Map { fn get(&amp;self, key: impl AsRef&lt;str&gt;) -&gt; &amp;Foo { self.map.get(key.as_ref()).unwrap() } fn create(&amp;mut self, key: impl Into&lt;String&gt;) -&gt; &amp;mut Foo { match self.map.entry(key.into()) { Entry::Vacant(entry) =&gt; entry.insert(Foo {}), _ =&gt; panic!(), } } fn get_or_create(&amp;mut self, key: impl Into&lt;String&gt;) -&gt; &amp;mut Foo { match self.map.entry(key.into()) { Entry::Vacant(entry) =&gt; entry.insert(Foo {}), Entry::Occupied(entry) =&gt; entry.into_mut(), } } } fn main() { let mut map = Map::default(); map.get_or_create("bar"); map.get_or_create("bar"); assert_eq!(map.map.len(), 1); } </code></pre> <p><a href="https://play.integer32.com/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=644a89e615a7503fc87742513b367816" rel="noreferrer">playground</a></p> <p>My problem is that in <code>get_or_create</code> a <code>String</code> will always be created, incurring unneeded memory allocation, even if it's not needed for an occupied entry. Is it possible to fix this in any way? Maybe in a neat way with <a href="https://doc.rust-lang.org/std/borrow/enum.Cow.html" rel="noreferrer"><code>Cow</code></a>?</p>
How do I resolve the error "no module in the root" when using a module in Rust 2018?
<p>I'm working on a project that is utilizing some local modules in folders under <code>src/</code>. I'm currently using Rust 2018 edition and one of the major changes for that is the <a href="https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-clarity.html" rel="noreferrer">handling of imports/<code>use</code> statements</a>.</p> <p>My module code is all working correctly, but as I started to pull it together to be used for the project as a whole I started getting this error:</p> <pre class="lang-none prettyprint-override"><code>error[E0432]: unresolved import `crate::lexer` --&gt; src/main.rs:1:5 | 1 | use crate::lexer; | ^^^^^^^^^^^^ no `lexer` in the root </code></pre> <p>Currently, my code is set up like this:</p> <pre><code>src/ | main.rs | lexer/ | mod.rs | lexer.rs </code></pre> <p><strong>lexer/lexer.rs</strong></p> <pre><code>pub fn lex_stuff() -&gt; Vec&lt;String&gt; { vec![String::new("test")] } </code></pre> <p><strong>lexer/mod.rs</strong></p> <pre><code>pub mod lexer; </code></pre> <p><strong>main.rs</strong></p> <pre><code>use crate::lexer; fn main() { println!("Hello, world!"); lexer::lexer::lex_stuff(); } </code></pre> <p>I've attempted to resolve this by changing the statement to <code>use lexer</code> as well as <code>use self::lexer</code> and adding <code>extern crate lexer</code> (which obviously doesn't work, but what the heck, figured I'd try it). However, none of these have worked.</p> <p>What can I do to resolve the <code>no 'lexer' in the root</code> error?</p>
How to compare contents an owned vector to a static vector in Rust?
<p>As a part of a test, I want to assert that a function returns a vector with proper contents. I therefore made the expected data available as a static variable. However, I can't find a proper way to compare the contents of a managed vector to the static vector variable.</p> <pre><code>#[test] fn test_my_data_matches_expected_data () { static expected_data: [u8, ..3] = [1, 2, 3]; let my_data: ~[u8] = ~[1, 2, 3]; // actually returned by the function to test // This would be obvious, but fails: // -&gt; mismatched types: expected `~[u8]` but found `[u8 * 3]` assert_eq!(my_data, expected_data); // Static vectors are told to be available as a borrowed pointer, // so I tried to borrow a pointer from my_data and compare it: // -&gt; mismatched types: expected `&amp;const ~[u8]` but found `[u8 * 3]` assert_eq!(&amp;my_data, expected_data); // Dereferencing also doesn't work: // -&gt; type ~[u8] cannot be dereferenced assert_eq!(*my_data, expected_data); // Copying the static vector to a managed one works, but this // involves creating a copy of the data and actually defeats // the reason to declare it statically: assert_eq!(my_data, expected_data.to_owned()); } </code></pre> <hr> <p><strong>Update:</strong> Assigning a reference to the static vector before comparing it works around the problem, so I ended up with a small macro to assert equality of vectors:</p> <pre><code>macro_rules! assert_typed_eq (($T: ty, $given: expr, $expected: expr) =&gt; ({ let given_val: &amp;$T = $given; let expected_val: &amp;$T = $expected; assert_eq!(given_val, expected_val); })) </code></pre> <p>Usage: <code>assert_typed_eq([u8], my_data, expected_data);</code></p>
How can I `flatmap` streams in Rust?
<p>I have a <a href="https://docs.rs/rusoto_core/0.36.0/rusoto_core/struct.ByteStream.html" rel="nofollow noreferrer"><code>rusoto_core::ByteStream</code></a> which implements <a href="https://docs.rs/futures/0.1.25/futures/stream/trait.Stream.html" rel="nofollow noreferrer">futures' <code>Stream</code> trait</a>:</p> <pre><code>let chunks = vec![b"1234".to_vec(), b"5678".to_vec()]; let stream = ByteStream::new(stream::iter_ok(chunks)); </code></pre> <p>I'd like to pass it to <a href="https://docs.rs/actix-web/0.7.18/actix_web/dev/struct.HttpResponseBuilder.html#method.streaming" rel="nofollow noreferrer">actix_web's <code>HttpResponseBuilder::streaming</code></a> method.</p> <pre><code>use actix_web::dev::HttpResponseBuilder; // 0.7.18 use rusoto_core::ByteStream; // 0.36.0 fn example(stream: ByteStream, builder: HttpResponseBuilder) { builder.streaming(stream); } </code></pre> <p>When I try to do it I receive the following error:</p> <pre class="lang-none prettyprint-override"><code>error[E0271]: type mismatch resolving `&lt;rusoto_core::stream::ByteStream as futures::stream::Stream&gt;::Item == bytes::bytes::Bytes` --&gt; src/main.rs:5:13 | 5 | builder.streaming(stream); | ^^^^^^^^^ expected struct `std::vec::Vec`, found struct `bytes::bytes::Bytes` | = note: expected type `std::vec::Vec&lt;u8&gt;` found type `bytes::bytes::Bytes` </code></pre> <p>I believe the reason is that <code>streaming()</code> expects a <code>S: Stream&lt;Item = Bytes, Error&gt;</code> (i.e., <code>Item = Bytes</code>) but my <code>ByteStream</code> has <code>Item = Vec&lt;u8&gt;</code>. How can I fix it?</p> <p>I think the solution is to <code>flatmap</code> my <code>ByteStream</code> somehow but I couldn't find such a method for streams.</p> <p>Here's an example how <code>streaming()</code> can be used:</p> <pre><code>let text = "123"; let (tx, rx_body) = mpsc::unbounded(); let _ = tx.unbounded_send(Bytes::from(text.as_bytes())); HttpResponse::Ok() .streaming(rx_body.map_err(|e| error::ErrorBadRequest("bad request"))) </code></pre>
How can I push an iterator to an existing vector (or any other collection)?
<p>Looking through the documentation or Rust 0.12, I saw <a href="https://doc.rust-lang.org/0.12.0/collections/vec/struct.Vec.html#method.push_all" rel="noreferrer">the following method</a> to push multiple values to an already existing <code>Vec</code>:</p> <pre><code>fn push_all(&amp;mut self, other: &amp;[T]) </code></pre> <p>However, if I have an iterator, I don't think it is efficient to use: <code>vector.push_all(it.collect().as_ref())</code>. Is there a more efficient way?</p>