FAQ Database Discussion Community


Borrowed value does not live long enough

rust
This is my code extern crate postgres; use postgres::{Connection, SslMode}; struct User { reference: String, email: String } static DB_URI: &'static str = "postgres://postgres:[email protected]/test"; fn main() { let conn = Connection::connect(DB_URI, &SslMode::None).unwrap(); let trans = conn.transaction().unwrap(); let user = User { reference: "123abc".to_string(), email: "[email protected]".to_string() }; let result = insert_user(&trans,...

Can Rust handle cyclic data structures without any garbage collector?

rust
Is it possible to completely avoid a garbage collector and manual deallocation? Is it possible to implement an interpreter for a language that needs garbage collection (say, Scheme) in Rust, without implementing or using any garbage collector? ...

Calling an impl method from another impl method

rust
It seems I can't call the method of the same struct in Rust or maybe I don't understand something: struct St1 { aa: String } impl St1 { pub fn method1() -> String { //.... method2() //error: unresolved name method2 } pub fn method2() -> String { //.... } }...

Can I create a macro that unrolls loops?

macros,rust
I'm trying to write some fast matrix code in Rust and to do this needs to ensure that loops are unrolled. Is there a way to create a compile-time for-loop? E.g: I want unroll_loop!(f, a, 3); to generate f(a, 0); f(a, 1); f(a, 2); ...

How do I implement a function which prints a vector of any type and length?

rust
I am trying to implement a function which takes a vector of any type and any lengths to print it. This is my implementation right now: fn print_vec<T>(v: &T) { for i in v.iter() { println("{}",i); } } fn main() { let vec = [1,2,3]; print_vec(vec); } but I get...

Pass Python list to Rust function

python,rust,ffi
I have a Rust library that needs to be imported into Python via the ctypes module. My goal is to use Rust functions that take Vec<T> / i32 as arguments and return those types, from Python. Currently, I can pass integers to the Rust functions, and have them return lists...

vector method push_all is not found for a custom struct

rust
So in this simple example #![feature(collections)] struct User { reference: String, email: String } fn main() { let rows = vec![ vec!["abcd".to_string(), "[email protected]".to_string()], vec!["efgh".to_string(), "[email protected]".to_string()], vec!["wfee".to_string(), "[email protected]".to_string()], vec!["rrgr".to_string(), "[email protected]".to_string()] ]; let mut rows_mut: Vec<Vec<String>> = Vec::new(); rows_mut.push_all(&rows); let mut users_mut: Vec<User> = Vec::new(); let users = vec![ User { reference:...

How do I import from a sibling module?

import,rust,use
In src/lib.rs I have the following extern crate opal_core; mod functions; mod context; mod shader; Then in src/context.rs I have something like this, which tries to import symbols from src/shader.rs: use opal_core::shader::Stage; use opal_core::shader::Shader as ShaderTrait; use opal_core::GraphicsContext as GraphicsContextTrait; use functions::*; // this import works fine use shader::*; //...

Correct idiom for freeing repr(C) structs using Drop trait

c,memory,rust
This code works fine but gives a compiler warning on Rust nightly (1.2) #[repr(C)] struct DbaxCell { cell: *const c_void } #[link(name="CDbax", kind="dylib")] extern { fn new_dCell(d: c_double) -> *const c_void; fn deleteCell(c: *const c_void); } impl DbaxCell { fn new(x: f64) -> DbaxCell { unsafe { DbaxCell { cell:...

Why does Drop take &mut self instead of self?

rust
Why does Drop’s method have signature fn drop(&mut self) instead of fn drop(self)? This makes it difficult to move values out of the fields e.g. self.join_handle.join() or std::mem::drop(self.file) (error: cannot move out of type X, which defines the Drop trait).

Lifetime parameters for an enum within a struct

struct,enums,rust,lifetime
I don't understand why I get an error with this type of structure enum Cell <'a> { Str(&'a str), Double(&'a f32), } struct MyCellRep<'a> { value: &'a Cell, ptr: *const u8, } impl MyCellRep{ fn new_from_str(s: &str) { MyCellRep { value: Cell::Str(&s), ptr: new_sCell(CString::new(&s)) } } fn new_from_double(d: &f32) {...

What does & actually do?

rust
I am trying to understand Rust's reference. fn main() { let x: i32 = 0; println!("{}", x+1); // this works println!("{}", (&x)+1); // this works //println!("{}", (&(&x))+1); // but this failed } What I get: 1 1 What does & actually do? Why can &x be added like it is...

Closing stdout or stdin

rust
Since files and streams are closed automatically when being dropped, but io::stdin() only provides a handle to the underlying stream, I fail to see how to explicitly close stdin or stdout or detect EOF on stdin in my program. Consider fn main() { let mut stdin = io::stdin(); let mut...

Create a vector from iterating hashmap

rust
What is the optional way in Rust to iterate a HashMap and collect the result into a Vec? This is my attempt so far: use std::collections::HashMap; struct User { reference: String, email: String } fn main() { let mut users: HashMap<String, User> = HashMap::new(); users.insert("first".to_string(), User { reference: "ref1".to_string(), email:...

Detecting client hangup in MIO

rust,mio
When using MIO (0.3.5) how do I detect the termination of a connection? I tried the following: extern crate mio; use mio::{EventLoop,Token,ReadHint}; use std::io::Read; fn main(){ let listener = mio::tcp::TcpListener::bind("localhost:1234").unwrap(); let (stream,_) : (mio::tcp::TcpStream, _) = listener.accept().unwrap(); let mut event_loop = EventLoop::new().unwrap(); event_loop.register(&stream,Token(0)).unwrap(); println!("run..."); event_loop.run(&mut H{stream:stream}).unwrap(); } struct H{stream :...

Linking to a static lib compiled with MSVC

dll,rust
I'm trying to link with a simple C lib on windows against Rust library My lib is .h extern "C" { void say_hello(const char* s); } .cpp #include <stdio.h> void say_hello(const char* s) { printf("hello world"); } My Rust file #[link(name="CDbax", kind="static")] extern "C" { fn say_hello(s: *const libc::c_char) ->...

Implementing a generic conversion from an object implementing the `Error` trait

rust
I cannot get the following code to compile. I get an error that From is already implemented. If I remove the manual impl of From I get the error that From is not implemented. If I do not implement Error it works fine. I suppose that this is due to...

Stack behavior when returning a pointer to local variable

stack,rust
I have a simple example where the behaviour of Rust does not match my mental image, so I am wondering what am I missing: fn make_local_int_ptr() -> *const i32 { let a = 3; &a } fn main() { let my_ptr = make_local_int_ptr(); println!("{}", unsafe { *my_ptr } ); }...

Conditionally compile only one module at a time

rust
Sometimes while refactoring a change in one of the modules has impact on every other module (or many others), because say a type has been changed or a function parameter has been changed etc. In this case instead of changing everything and then compiling at once is there a way...

cannot move out of borrowed content - ref doesn't work [duplicate]

rust
This question already has an answer here: “cannot move out of borrowed context” and “use of moved value” 1 answer I have this code: enum MyEnum1 { val1, val2 } struct Struct1 { field1: MyEnum1, field2: String } fn fn1(a: Struct1, b: String, c: String) { let let1 =...

return a value from within an if statement in a match statement

rust
In the function below, I match the first full character of a &str, and if it is a *, -, or _ and if it is those that character is returned, and with the _ arm I want to check if the character is whitespace, and return 'a' if the...

Situations where Cell or RefCell is the best choice

rust
When would you be required to use Cell or RefCell? It seems like there are many other type choices that would be suitable in place of these, and the documentation warns that using RefCell is a bit of a "last resort". Is using these types a "code smell"? Can anyone...

Linking with a Windows library outside the build folder

windows,rust,ffi
Is there a way to link with a library that's not in the current package path. This link suggests placing everything under the local directory. Our packages are installed in some repository elsewhere. I just want to specify the libpath to it on windows. authors = ["Me"] links = "CDbax"...

Why is `Sized` bound necessary in this trait?

rust,traits
I have a simple trait with two associated functions like this: trait WithConstructor : Sized { fn new_with_param(param: usize) -> Self; fn new() -> Self { Self::new_with_param(0) } } The default implementation of the second method (new()) force me to put the Sized bound on the type. Why ? (I...

How to find out what type a rustc::middle::ty::Ty represents?

plugins,rust,lint,internals
For writing yet another lint in Rust, I need to make sure that the type of an Expr is actually an Option<_> (or any pointer to one). I have already walked any ptrs and rptrs to their conclusion and am left with a rustc::middle::ty that in my test case debugs...

What's the difference between filter(|x|) and filter(|&x|)?

closures,rust
In the Rust Book there is an example of calling filter() on an iterator: for i in (1..100).filter(|&x| x % 2 == 0) { println!("{}", i); } There is an explanation below but I'm having trouble understanding it: This will print all of the even numbers between one and a...

How to use multiple variables in routes with Nickel?

rust,nickel
Nickel states that you can use variables in the URLs, which sounds very useful, but is it possible to use multiple variables? Something like: www.example.com/login/:userid?:apikey?:etc server.get("/start/:userid?:passwd", middleware! { |request| // format!("This is user: {:?} = {:?}", // request.param("userid"), // request.param("passwd") // ); }); ...

Casting to a generic type

rust
I have a newbie question about generics in Rust (version 1.0). Let's say I write a generic function to do division. Never mind the usefulness of such a function; it's a simple function to keep this question simple. fn divide<T: std::ops::Div>(a: T, b: T) -> T { a / b...

Access submodule from another submodule when both submodules are in the same main module

module,rust
I'm using rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14) and I've got the following setup: my_app/ | |- my_lib/ | | | |- foo | | |- mod.rs | | |- a.rs | | |- b.rs | | | |- lib.rs | |- Cargo.toml | |- src/ | |- main.rs |...

Recovering from `panic!` in another thread

rust
I know that in Rust there is no try/catch, and you can't throw a rolling save from the thread that is currently panicking. I know you should not create and handle errors like this. This is just for example's sake. However, I am wondering what the best way to recover...

Renaming a crate with a hyphen doesn't compile anymore

rust
This no longer compiles: extern crate "my-crate" as my_crate1; What's the new syntax? I did not find anything by searching....

What is the difference between Slice and Array

arrays,rust,slice,coercion
I am a newbie to Rust programming language. Why are both &[u8] and &[u8; 3] ok in this example? fn main() { let x: &[u8] = &[1u8, 2, 3]; println!("{:?}", x); let y: &[u8; 3] = &[1u8, 2, 3]; println!("{:?}", y); } EDIT: The fact that &[T; n] can coerce...

“conflicting implementations for trait” when trying to be generic

types,rust
Background: I'm using the nalgebra library and I want to create a structure that represents a multivariate normal distribution. M is the type of the matrix, e.g. Mat4<f64>. My current attempt looks like this: use std::ops::Mul; use std::marker::PhantomData; use nalgebra::*; #[allow(non_snake_case)] pub struct Multivar𝒩<N, V, M: SquareMat<N, V>> { μ:...

Disabling default namespaces

namespaces,rust
Rust seems to use some namespaces by default. For example, I don't have to use std::string::String and can simply type String. How can I define my own struct String without clashing with std::string::String? And where can I find a list of the namespaces that are included by default?

Struct that owns some data and a reference to the data [duplicate]

rust,object-lifetime,borrow-checker
This question already has an answer here: How to initialize struct fields which reference each other 1 answer Construction of an object allocates data needed for lifetime of that object, but also creates another object that needs to keep references to the data: pub fn new() -> Obj {...

How to convert iterator of chars to String?

rust
I need something like .collect() but which will produce String instead of container of chars, i.e. I need an inverse of chars(). I cannot find anything suitable in the documentation. Of course I can implement such a function myself but I'm sure there must be standard solution to this problem....

Getting 'Missing Lifetime specifier' error

compiler-errors,rust,lifetime
This is my code: use std::ptr; struct Query<T>{ data: T, prev: & Query<T>, next: & Query<T>, } impl<T> Query<T>{ fn new(name: T) -> Query<T>{ Query{ data: name, prev: ptr::null(), next: ptr::null(), } } } I keep getting 'missing lifetime specifier' where I am referencing &Query<T>. How do I fix this...

Indexing a String

rust
I want to perform a very simple task, but I cannot manage to stop the compiler from complaining. fn transform(s: String) -> String { let bytes = s.as_bytes(); format!("{}/{}", bytes[0..2], bytes[2..4]) } [u8] does not have a constant size known at compile-time. Some tips making this operation to work as...

How can I create Haskell-like functional dependencies

rust
Background: I'm using the nalgebra library and I want to create a structure that represents a multivariate normal distribution. The number and row type is uniquely determined by a square matrix type, so I want to write something like this: #[allow(non_snake_case)] pub struct Multivar𝒩<M: SquareMat<N, V>> { μ: V, Σ:...

Getting a single character out of a string

string,rust
I want to get the first character of a std::str. The method char_at() is currently unstable, as is slice_chars in std::string::String. The only option I have currently come up with is the following. let text = "hello world!"; let char_vec:Vec<char> = text.chars().collect(); let ch = char_vec[0]; But this seems excessive...

Return Trait From Method

rust,trait
I'm trying to create a function that returns a trait, in this case the shader Shader (which in the below code example is used as ShaderTrait). However I receive the following error: error: the trait core::marker::Sized is not implemented for the type opal_core::shader::Shader This makes sense as the compiler doesn't...

Does <'a, 'b: 'a> mean that the lifetime 'b must outlive the lifetime 'a?

rust,lifetime
I want to implement a builder similar to the debug builders defined by the standard library. They are defined using structures like the following: struct DebugFoo<'a, 'b: 'a> { fmt: &'a mut std::fmt::Formatter<'b> } Since I don't understand what the form <'a, 'b: 'a> means nor I can find it...

More convenient way to work with strings in winapi calls

string,winapi,rust
I'm looking for more convenient way to work with std::String in winapi calls in Rust. Using rust v 0.12.0-nigtly with winapi 0.1.22 and user32-sys 0.1.1 Now I'm using something like this: use winapi; use user32; pub fn get_window_title(handle: i32) -> String { let mut v: Vec<u16> = Vec::new(); v.reserve(255); let...

Why do I have to expose a macro implementation's 'use' in the client library?

macros,rust
I'm trying to use a macro I've created in a separate module. With reference to this SO question, I've imported a macro fine. However it seems that I have Update to add macro implementation lib.rs #![macro_use] use std::fmt; use std::ffi::CString; use std::ffi::CStr; use std::str; extern crate libc; pub enum DbaxError...

The “trait Clone is is not implemented” when deriving the trait Copy for Enum

enums,copy,rust
The following code: #[derive(Copy)] enum MyEnum { Test } Is giving me this error: error: the trait core::clone::Clone is not implemented for the type MyEnum [E0277] Why is that the case, and how do I fix it?...

Filter vector in place

iterator,rust
In Rust is it possible to operate on a vector in-place? I'd like to remove some elements from a Vec, but vec.iter().filter().collect() creates a new vector with borrowed items. I'd like to mutate the original Vec without extra memory allocation (and keep memory of removed elements as an extra capacity...

Struct vs enum lifetime differences

rust,lifetime
Why does this work #[derive(Debug)] pub struct Foo<'a,'b> { s : &'a str, n : &'b i32 } #[test] fn test_struct() { let f = Foo { s : &"bar" , n : &17 }; println!("{:?}",f); } but this doesn't #[derive(Debug)] pub enum Bar<'a,'b> { Baz ( &'a str), Fub...

Implementing Deref on a struct that owns a boxed trait

rust
I'd like to implement Deref and DefrefMut on a struct that owns a boxed trait, e.g.: use std::ops::{Deref, DerefMut}; trait Quack { fn quack(&self); } struct QuackWrap { value: Box<Quack> } impl Deref for QuackWrap { type Target = Box<Quack>; fn deref<'a>(&'a self) -> &'a Box<Quack> { &self.value } }...

How can I send a function to another thread?

multithreading,unit-testing,rust
I am attempting to write a simpler unit test runner for my Rust project. I have created a TestFixture trait that my test fixture structs will implement, similar to inheriting from the unit test base class in other testing frameworks. The trait is fairly simple. This is my test fixture...

Why is an enum containing a Box not copiable?

rust
Boxes and arrays are copiable, so why does this not compile? #[derive(Debug, Copy, Clone)] enum Octtree{ Branch(Box<[Octtree; 8]>), Filled, Empty, } Compile error: main.rs:3:17: 3:21 error: the trait `Copy` may not be implemented for this type; variant `Branch` does not implement `Copy` [E0205] EDIT: Ok, so I don't want Octtree...

How do I configure the path to the Rust installation when using RustDT with Eclipse?

eclipse,rust
The RustDT github page says this: The Rust installation is required for project building. The path to the installation should be configured in Preferences/Rust. I go into Preferences/Rust in Eclipse, but I only see options for text/background colors and formatting settings. Where can I link the path to the installation?...

Passing self reference to method of owned object

rust,borrow-checker
Consider the following example: fn main() { let mut field = Field::new(Vector2d{x: 100, y: 100}); field.update(); } #[derive(Copy, Clone)] struct Vector2d { x: i32, y: i32, } struct Ball { radius: i32, position: Vector2d, velocity: Vector2d, } impl Ball { fn new(radius: i32, position: Vector2d, velocity: Vector2d) -> Ball {...

No error for two traits implementing the same method

rust,mio
According to the docs, Rust should complain if I try to call a method provided by two different traits like this: trait Foo { fn f(&self); } trait Bar { fn f(&self); } struct Baz; impl Foo for Baz { fn f(&self) { println!("Baz’s impl of Foo"); } } impl...

Bug in FFI when passing CString followed by an int

windows,rust,32-bit,ffi
My Rust test code extern "C" { fn test_int_only(n : libc::c_int); fn test_int_and_str(s : CString , n : libc::c_int); } pub fn test1() { unsafe { test_int_only(0); test_int_only(1); test_int_only(2); test_int_only(4); test_int_only(-12); } } pub fn test2() { unsafe { test_int_and_str(CString::new("Foo").unwrap(),0); test_int_and_str(CString::new("Bar").unwrap(),1); test_int_and_str(CString::new("Baz").unwrap(),2); test_int_and_str(CString::new("Fub").unwrap(),4); test_int_and_str(CString::new("Bub").unwrap(),-12); } } My C code void...

Modify Collection While Iterating Over it

rust
Gist to source Disclaimer: I'm just starting to learn Rust and I know this is not the best way to do this. I'm simply playing around to see what I can and cannot do. I'm also trying to limit any copying to restrict myself a little bit. I have a...

Result has no method called “unwrap()”?

rust
What a strange error: let res1 = get_res(); assert!(res1.is_ok()); assert_eq!("just for test", res1.unwrap()); //error The error is: type `core::result::Result<(MyStruct1, collections::btree::map::BTreeMap<collections::string::String, collections::string::String>), Error>` does not implement any method in scope named `unwrap` ...

What is the best variant for appending a new line in a text file?

file-io,rust
I'm new to Rust, and I am using this code to append a new line to the end of file: let text = "New line".to_string(); let mut option = OpenOptions::new(); option.read(true); option.write(true); option.create(true); match option.open("foo.txt") { Err(e) => { println!("Error"); }, Ok(mut f) => { println!("File opened"); let size =...

Traits in algebraic data types

rust
I'm having trouble understanding the rules about traits in algebraic data types. Here's a simplified example: use std::rc::Rc; use std::cell::RefCell; trait Quack { fn quack(&self); } struct Duck; impl Quack for Duck { fn quack(&self) { println!("Quack!"); } } fn main() { let mut pond: Vec<Box<Quack>> = Vec::new(); let duck:...

How can I open a file with the standard text editor?

rust
My console based program has a config file which can be opened and edited in a text editor. How would I open said config file with the default text editor? I know there is std::process, but I can't get it to work. The program should be able to run on...

How to implement variable increment via side effect?

rust,side-effects
For learning purposes, I tried this solution, but it does not work: use std::ops::Add; fn inc<T: Add>(x:&mut T) { *x += 1; } fn main() { let mut x:i32 = 10; let mut y:u8 = 1; inc(&mut x); inc(&mut y); println!("{} {}", x, y); } Error message: <anon>:4:5: 4:7 error:...

What is the most appropriate way to convert nibbles to a u64?

rust
I am trying to learn Rust and decided to write a program that converts a hex string into a u64. Currently, I have parsed the string into a vector of u8 values, each representing four bits (or "nibble"). I wrote the following code to take a Vec<u8> and return a...

Using a no-method trait implementation in a different module

rust
I have lib.rs: pub mod genetics { use std; pub trait RandNewable { fn new() -> Self; } pub trait Gene : std::fmt::Debug + Copy + Clone + RandNewable {} #[derive(Debug, Copy, Clone)] pub struct TraderGene { cheat: bool, } impl RandNewable for TraderGene { fn new() -> TraderGene {...

Rust: Lifetime of String from file [duplicate]

file,io,rust
This question already has an answer here: Return local String as slice 1 answer I'm trying to read in some external GLSL code into Rust. The reading works properly, but I run into a lifetime issue in the final expression (in the Ok(_) branch) error: s does not live...

Global feature gates in Cargo

rust,rust-cargo
I would like to enable a feature gate for my entire Cargo project. For example, I would like #![feature(non_ascii_idents)] added to every source file. Is there a place to list them in Cargo.toml?

Immutable reference after mutable borrow

rust
I've been reading about rust for the past week and (trying) to play around with it. It seems I run into similar problems related to ownership/borrowing every time I use it, so here is the simplest piece of code that sort of illustrates the usual problems. use std::cell::RefCell; struct Res...

“consider removing this semicolon” error

rust
While following the rustbyexample.com tutorial, I typed the following code: impl fmt::Display for Structure { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let x = format!("{}", "something"); write!(f, "OMG! {}", self.0); } } And got the following error from the compiler: format.rs:30:5: 32:6 error: not all control paths return...

Printing using fmt::Display

printing,rust
I am trying to print an enum (or structure) using fmt::Display. Though the code compiles and gets to the display method, it doesn't print the value. pub enum TestEnum<'a> { Foo(&'a str), Bar(f32) } impl<'b> fmt::Display for TestEnum <'b> { fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result { println!("Got...

Load a shared library linked to Rust library in R

r,shared-libraries,rust
Following up on this question here, I am having issues using dyn.load to load a shared library that is linked to a Rust dylib. I suspect it has something to do with where R is looking for the Rust dylib, but I have not found a way to specify another...

How to implement a factory trait that returns generic values with a matching type parameter?

rust
Question Consider the following code (simplified but compilable): use std::sync::Arc; pub trait ActorRef<Message> { /* ... */ } pub trait Actor<Message> { /* ... */ } pub trait ActorSpawner { /// Spawns a new actor returning an actor ref /// for passing messages to it. fn spawn<Message,A,R>(actor: A) -> Arc<R>...

Cannot infer appropriate lifetime for autoderef in Iterator impl

rust
I am trying to implement the Iterator trait for a struct which basically just acts as a borrower of an array of i32 values. However, I keep running into the compiler complaining about not being able to infer a lifetime inside the next method. I am aware of this answer,...

Return a moving window of elements resulting from an iterator of Vec

iterator,rust
I'm trying to figure out how to return a window of elements from a vector that I've first filtered without copying it to a new vector. So this is the naive approach which works fine but I think will end up allocating a new vector from line 5 which I...

Value does not live long enough when using multiple threads

rust
This is a simplified example of my situation: use std::sync::mpsc::{Sender, Receiver}; use std::sync::mpsc; use std::thread; struct User { reference: String, email: String } fn main() { let rows = vec![ vec!["abcd", "[email protected]"], vec!["efgh", "[email protected]"], vec!["wfee", "[email protected]"], vec!["rrgr", "[email protected]"] ]; let chunk_len = (rows.len() / 2) as usize; let mut chunks...

Rust - String concatenation [duplicate]

string,concatenation,rust
This question already has an answer here: How do I concatenate strings? 1 answer I started programming with Rust this week and I am having a lot of problems understanding how Strings work. Right now, I am trying to do a simple program that prints a list of players...

Create shared C object linked to Rust dylib for use in R

c++,c,r,rust,ffi
I am trying to create a shared object I can load into R that calls Rust functions by way of R's C API. To call Rust from C, I am following this blog post. My problem arises when I try to create the shared library and link to the Rust...

Generic fn, channel, and thread spawn

closures,rust,lifetime
I have this code here: (Playground link) use std::thread; use std::sync::mpsc::channel; fn run<T: Send>(task: fn() -> T) -> T { let (tx, rx) = channel(); thread::spawn(move || { tx.send(task()); }); rx.recv().unwrap() } fn main() { let task = || 1 + 2; let result = run(task); println!("{}", result); } But...

Rustc/LLVM generates faulty code for aarch64 with opt-level=0

rust,qemu,arm64,osdev
I have two files which are assembled/compiled/linked into minimalistic kernel. start.s: .set CPACR_EL1_FPEN, 0b11 << 20 .set BOOT_STACK_SIZE, 8 * 1024 .global __boot_stack .global __start .global __halt .bss .align 16 __boot_stack: .fill BOOT_STACK_SIZE .text __start: /* disable FP and SIMD traps */ mov x0, #CPACR_EL1_FPEN msr cpacr_el1, x0 /* set...

Lifetime of a mutable element in struct

rust
How can I define a mutable element in a struct? If I have a following example struct User<'a> { reference: String, email: String, addresses: &'a mut Vec<Address> } struct Address { street: String, city: String } fn main() { let mut users = Vec::new(); users.push(User { reference: "ref".to_string(), email: "[email protected]".to_string(),...

Right way to set up Rust using Vim

vim,rust,rust-cargo
I've finally started to dive into Rust and want to clarify some issues when it comes to setting up everything nicely. I'm using vim on Linux and found a nice plugin for syntax highlighting. Autocompletion is somewhat troublesome though, using phildawes/racer. The plugin needs the src location for Rust which...

Moving Arc Mutex Ncurses window down thread still doesn't implement send

concurrency,rust,ncurses
I'm building an ncurses interface for a little thing I'm working on. For the input, I want to read it non blocking. I figured I could wrap the WINDOW in an Arc Mutex but this doesn't seem to work, as it still complains about send. Is this because the implementation...

Why do I need to use self::core::ops?

rust
I'm trying to use Mul from core. This is suggested by the compiler and works: extern crate core; use self::core::ops::Mul; but why doesn't extern crate core; use core::ops::Mul; work? I get the error error: unresolved import `core::ops::Mul`. Did you mean `self::core::ops`?...

Cargo dependency version syntax

rust,rust-cargo
Is there a page documenting the different Cargo syntax for dependencies? So far I have seen three... [dependencies] crate = "1.0.0" # I think this is an exact version match crate = "^1.0.0" # I think this means "use that latest 1.x.x" crate = "*" # I think this means...

remove duplicates from vector of custom struct

rust
I'm trying to remove duplicates in the below example: struct User { reference: String, email: String } fn main() { let mut users: Vec<User> = Vec::new(); users.push(User { reference: "abc".into(), email: "[email protected]".into() }); users.push(User { reference: "def".into(), email: "[email protected]".into() }); users.push(User { reference: "ghi".into(), email: "[email protected]".into() }); users.sort_by(|a, b| a.email.cmp(&b.email));...

How to combine different algorithms in one executable

rust
To learn Rust, I have started to implement some of the Project Euler problems. Now I want to take the next step and create a console based user interface, which has the ability for running all or only specific problems. Another requirement is that the user should be able to...

How are the generic functions and types stored in an rlib?

generics,rust
In C++, the templates can not be generated into dynamic libraries, we can only use them by header files. In C#, generic functions and types can be interpreted by intermediate language in .NET. Rust has no virtual machine, and the generics can be stored in the rlib files. How does...

Use of undeclared type that is defined in another file

rust
So, I have a hierarchy of files that have their own classes. Here is an example: mod query; struct Row<T>{ data: Vec<Query<T>>, } impl<T> Row<T>{ fn new(array: Vec<Query<T>>) -> Row<T>{ Row{ data: array, } } } Although it says the files are there, it says that "Query is an undeclared...

Why can associated constants not depend on type parameters?

rust
Is this just a current limitation or is there a technical reason? As generic functions get compiled to specialized code, I don’t see what should prevent it from working. It also works fine in the main function. Example (playground): #![feature(associated_consts)] trait HasNumber<T> { const Number: usize; } enum One {}...

Threaded calling of functions in a vector

multithreading,function,rust,borrow-checker
I have an EventRegistry which people can use to register event listeners. It then calls the appropriate listeners when an event is broadcast. But, when I try to multithread it, it doesn't compile. How would I get this code working? use std::collections::HashMap; use std::thread; struct EventRegistry<'a> { event_listeners: HashMap<&'a str,...

Reading immutable value inside spawned thread

rust
I'm trying to make this example work use std::sync::mpsc::{Sender, Receiver}; use std::sync::mpsc; use std::thread; use std::sync::Arc; struct User { reference: String, email: String } struct UserIndex { reference: usize, email: usize } fn main() { let rows = vec![ vec!["abcd", "[email protected]"], vec!["efgh", "[email protected]"], vec!["wfee", "[email protected]"], vec!["rrgr", "[email protected]"] ]; let user_index...

Writing Vec to a file

rust
I'm having trouble on writing Vec<u16> content to a file. #[derive(Debug, Copy, Clone, PartialEq)] pub enum ImageFormat { GrayScale, Rgb32, } #[derive(Debug, Copy, Clone, PartialEq)] pub struct ImageHeader { pub width: usize, pub height: usize, pub format: ImageFormat, } pub struct Image { pub header: ImageHeader, pub data: Vec<u16>, }...

match expression falling through?

pattern-matching,rust
Here is some contrived but simple pattern matching example (demo): fn main() { let x = 'a'; match x { 'a'...'b' if false => { println!("one"); }, 'a' => { println!("two"); }, 'a'...'b' => { println!("three"); }, _ => panic!("what?") } } When I run it, I get three as...

How to reverse after zip two chains

rust
I have the following code which does not compile. fn main() { let a = "123" .chars() .chain("4566".chars()) .zip( "bbb" .chars() .chain("yyy".chars())) .rev() .map(|x, y| y) .collect::<String>(); println!("Hello, world! {}", a); } Got error like following: src/main.rs:37:10: 37:15 error: the trait `core::iter::ExactSizeIterator` is not implemented for the type `core::iter::Chain<core::str::Chars<'_>, core::str::Chars<'_>>`...

Is it possible to share data with threads without any cloning?

multithreading,rust,borrow-checker
Often when I'm delegating work to threads I have a piece of data that will outlive all of the threads. An example would be numbers in the following example: use std::thread; fn main() { let numbers = vec![1, 2, 3]; let thread_a = thread::spawn(|| { println!("{}", numbers.len()); }); let thread_b...

Implement Debug trait for large array type

rust,traits
I gather that Rust provides Debug impl's for arrays size 32 and smaller. I also gather that I could implement Debug on a larger array by simply using write! with a very long format specifier. But I'm wondering if there's a better way. What is the recommended method for implementing...

Using Rust returned array in Python using ctypes

python,rust,ctypes
I have a Rust function that returns an array and I want to use this array in Python, it could be a list or numpy.array it does not really matter. My Rust function looks like this: #[no_mangle] pub extern fn make_array() -> [i32; 4] { let my_array: [i32; 4] =...

What is the idiomatic way to write a linked list with a tail pointer?

linked-list,rust,reference-counting
As a learning project for Rust, I have a very simple (working, if incomplete) implementation of a singly linked list. The declaration of the structs looks like this: type NodePtr<T> = Option<Box<Node<T>>>; struct Node<T> { data: T, next: NodePtr<T>, } pub struct LinkedList<T> { head: NodePtr<T>, } Implementing size and...

Is it possible to find an element in a Vec and remove it?

vector,rust
In Rust, is there an in built function for finding and removing elements of a vector, both simultaneously and as separate actions? For example: for f in factors { if f in list { list.remove(f); } } Currently, the rust documentation is still a tad confusing, so while my search...

How to use closures in nested map?

closures,rust
I am trying to make a 2-dimensional matrix from a functor that creates each element, and store it as a flat Vec (each row concatenated). I used nested map (actually a flat_map and a nested map) to create each row and concatenate it. Here is what I tried: fn make<T,F>(n:...

the type of this value must be known in this context

rust
I want to get a length of a string which I've split: fn fn1(my_string: String) -> bool { let mut segments = my_string.split("."); if segments.collect().len() == 55 { //...... } // error: the type of this value must be known in this context How can I fix that error?...

Can I mark a function as deprecated?

rust
I'd like to mark functions/methods as deprecated. I tried to apply the deprecated attribute: #[deprecated] fn old_way_of_doing_it() { but this yields an error: error: stability attributes may not be used outside of the standard library Is there a way in which I can have the compiler warn a consumer of...

How can I wrap any impl of std::error::Error to ease error propagation?

rust
I'm trying to simplify the error flow in a webapp I'm working on, and my plan was to make a struct that implements std::error::Error and just forwards the result of description() for whatever kind of error it's wrapped around. I've implemented From for the types of errors I want to...