w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » RUST » Page 1
Iterating over the contents of an Option, or over a specific value
Unfortunately, it is impossible to use different iterators directly or with trait objects (which have recently been changed to disallow instantiation of trait objects with inappropriate methods i.e. ones which use Self type in their signature). There is a workaround for your particular case, however. Just use enums: fn stream(dst: &mut [u8], src: Option<&[u8]>) { static EMPTY: &

Categories : Rust

rust: error: macro undefined: 'fail!'
It has been renamed to panic!, see Issue 17489 and the nightly doc

Categories : Rust

Borrow pointer of a value which will be moved in a struct
I imagine you know what you're doing, but that doesn't seem like the best design to use with Rust. You say a Programmer should hold a reference to a Designer in order to ping them, but I imagine that pinging them implies mutating the Designer in some way (e.g. imagine some is_pinged field on the Designer), which you can't do via a simple reference. All you can do through a regular, immutable refer

Categories : Rust

Using from_iter to create BTreeSet in rust
Looks like it needs to be qualified with the name of the trait: let bset: BTreeSet<uint> = FromIterator::from_iter(triangles); But I think it's more idiomatic to use .collect(): let bset: BTreeSet<uint> = range(1, 10).map(|x| x*(x+1)/2).collect();

Categories : Rust

How to copy a folder recursively in Rust?
You could recursively walk the directory structure using std::io::fs::walk_dir, which yields an iterator in a Result, and for each Path, check if it's a file using the is_file() method provided by the PathExtensions extension trait. If it is, then use std::io::fs::copy to actually copy the file.

Categories : Rust

How does context switch in Rust's green threads work?
UPDATE November 20, 2015: Rust no longer uses green threading, and hasn't for a long time. The documentation page for green might help. Keep in mind that Rust has just about moved away entirely from a green-threads runtime, so whatever information you do find may be outdated or simply no longer be relevant. It may be reworked at a later date, but for now the focus is on a native, direct implemen

Categories : Rust

"associated types may not be referenced here"
Looks like a bug, I filed #18996. Associated items are very raw at the moment, issue #17307 summarises how much there is to go.

Categories : Rust

How can I unify the lifetimes between a struct and a trait?
You'll need to give the trait itself a lifetime parameter: trait Expression<'d> { fn evaluate(&self, context: &Context<'d>) -> Value<'d>; } impl<'d> Expression<'d> for Constant<'d> { fn evaluate(&self, _unused: &Context<'d>) -> Value<'d> { self.value } } Playpen The reason you're getting error #1 (beside

Categories : Rust

How to create a non consuming iterator from a Vector
I'm not sure what you're asking here. .iter() creates an iterator (Items) which does not move the Vec (You'll get an Iterator over &T). Filter (and most other iterator adapters) are lazy. Perhaps you should chain() the two iterators before filtering them? Otherwise, if you don't want the Filter to be consumed, clone it.

Categories : Rust

Rust package with both a library and a binary?
Tok:tmp doug$ du -a 8 ./Cargo.toml 8 ./src/bin.rs 8 ./src/lib.rs 16 ./src Cargo.toml: [package] name = "mything" version = "0.0.1" authors = ["me <me@gmail.com>"] [lib] name = "mylib" path = "src/lib.rs" [[bin]] name = "mybin" path = "src/bin.rs" src/lib.rs: pub fn test() { println!("Test"); } src/bin.rs: extern crate mylib; use mylib::test; pub fn main() { test(); }

Categories : Rust

Enums with constructions in Rust
Edit: I wasn't aware that Java enums were closed. As such, you should probably go with delnan's answer. I think you want something like this: pub struct Direction { angle: int, } impl Direction { pub fn new(angle: int) -> Direction { Direction { angle: angle, } } pub fn get_angle(&self) -> int { self.angle } } pub const EAST:

Categories : Rust

A built-in Object in Rust
If you want a HashMap that can mix values of many different types, you'll have to use Any. The most direct equivalent to Map<String, Object> would be HashMap<String, Box<Any>>. I switched &str to String because &str without a lifetime is probably not what you want and in any case even further removed from Java String than Rust's String already is. However, if you simply

Categories : Rust

Closure requires unique access to lambda function
The full error message is: <anon>:2:7: 2:8 error: closure requires unique access to `f` but it is already borrowed <anon>:2 f(f(x)) ^ <anon>:2:5: 2:6 note: previous borrow of `f` occurs here; the unique capture prevents subsequent moves or borrows of `f` until the borrow ends <anon>:2 f(f(x)) ^ <anon>:2:12: 2:12 note: previous borr

Categories : Rust

Rust - how to retrieve a user-defined type from for loop
You are experiencing the basis of Rust memory model : every object can (and must!) be owned by only exactly one other object most types are never implicitly copied and always moved (there are some exceptions : types being Copy) Take this code for example: let x = String::new(); let y = x; println!("{}", x); it generates the error: <anon>:4:20: 4:21 error: use of moved value: `x` <

Categories : Rust

Rust string lifetimes and iterator adapters (lifetime compile error)
The x &str is a reference to the contents of a String, the ones yielded by lines(). A &str can only live as long as the String it is a reference into, and you’re not storing the String anywhere. You would need to either store the lines in another variable: let lines = file.lines().map(|x| x.unwrap()).collect::<Vec<_>>(); let instances: Vec<Vec<&str>> = lines.

Categories : Rust

cannot borrow `*self` as mutable because it is also borrowed as immutable
I guess I found the reason. This is HashMap definition: pub struct HashMap<K, V, H = RandomSipHasher> { // All hashes are keyed on these values, to prevent hash collision attacks. hasher: H, table: RawTable<K, V>, // We keep this at the end since it might as well have tail padding. resize_policy: DefaultResizePolicy, } This is Vec definition: pub struct Vec<

Categories : Rust

In Rust, how can I fix the error "the trait `core::kinds::Sized` is not implemented for the type `Object+'a`"
The fundamental problem here is this: You want to store a vector of Objects. Now, a vector is a flat array: Each entry comes after another. But Object is a trait, and while you have only implemented it for Ball, you could implement it for Hats and Triangles too. But those might be different sized in memory! So Object, on its own, doesn't have a size. There are two ways of fixing this: Make

Categories : Rust

rust - std::string::String as a byte string (i.e. b"foo" or deprecated bytes!("foo"))
The .something() you want is called .as_slice(). Generally the word for a &[T] in rust is a slice, and the naming convention to cheaply borrow a type as another (in this case, from a Vec<T>) is .as_foo(). In this new comparison, you are comparing &[u8], instead of allocating a new Vec to compare. This should be much more efficient as well as more readable, since no allocation is n

Categories : Rust

Working with Mutable Borrows in Rust
Since you're working with str::chars(), and char is Copy, you can just dereference it in map(): fn tokenize_string(&mut self) { loop { let r = self.it.peek().map(|c| *c); let n = match r { Some(_) => self.it.next(), None => break }; // whatever } } Or if you just want to check if the iterator has returned something, use i

Categories : Rust

Trying to implement core::fmt::Show
The error is telling you that the method fmt does not have the type it expects, and in particular it found a &-ptr (i.e., the &str) where there should be a FormatError. changing the method signature to this will fix your compilation error: fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::FormatError> I have sent a pull request on github that makes this change (and

Categories : Rust

Lifetimes in traits
You are trying to do some king of inheritance-like pattern with trait, which is not really how they work. You can think of traits as somehow similar to interfaces provided by some languages : they are only a guaranty that your struct will provide some methods. The syntax trait Foo : Bar does not mean that somehow the trait Foo is a superset of trait Bar, and that implementing Foo for a struct wi

Categories : Rust

Returning reversed string from function [Rust]
The lifetime issue is similar to The lifetime of &str makes comparison hard: if you create a new object, it's a new object, uncorrelated from the old one. Therefore, you have two choices: either create a completely new object: input.chars().rev().collect() for example or reverse the input in-place, which requires it to be mut of course The former looks easy: fn reverse_new(input: &st

Categories : Rust

Rust borrow mutable self inside match expression
Let's fix the design issues first. The main issue is lifetime conflation: struct Top<'t> { list: Vec<Element<'t>>, } impl<'t> Top<'t> { fn add(&'t mut self, p_name:&'t str) -> Box<Element>; fn add_once(&'t mut self, p_name:&'t str) -> Box<Element>; } Here, you assert that self should live at least as long as 't, w

Categories : Rust

PNaCl support for Rust
AFAIK, there are currently no efforts to make Rust work with PNaCl. There are efforts however to eventually remove the necessity of an LLVM fork for Rust. This should make PNaCl support easier when it happens.

Categories : Rust

How do you create an iterator using a closure in rust?
This requires higher-rank lifetimes, since the lifetime in the closure should not be part of the type signature: the closure just wants to take &'a mut S for any lifetime 'a (since it needs to call the function with data that is only guaranteed to last for the interior of the next method: nothing nameable externally), not the lifetime exposed (and somewhat controllable) externally in the type

Categories : Rust

Rust not running helloworld example
Rust is a compiled language. rustc is the compiler, which takes a source file and produces a binary which can then be executed; it does not itself execute the code, however. You must take the binary it produces (by default, the source filename minus the .rs extension) and execute it yourself with ./main or similar. If you use Cargo, there is cargo run which compiles the code if necessary and then

Categories : Rust

How to sort a vector in Rust?
A mutable slice of elements with a total ordering has a sort method. Because Vec<T> implements DerefMut<[T]>, you can call this method directly on a vector, so vector.sort() works.

Categories : Rust

Can you coerce Some(box|:|) to Option>> in rust?
It is worth noting that this is a general property of trait objects and generic structs/enums, and is not at all specific to unboxed closures, FnOnce, Option or |:| (especially not this, since it is just a nice way to create a value implementing a certain trait). Also, the recent RFC #401 is related. 1) Should the above code work? Or does Option<>/Some() imply something complex that I have

Categories : Rust

How can I create an is_prime function that is generic over various integer types?
Generic number types can be quite a nuisance to work with, but once you get the hang of them they don’t tend to be too bad, though a little more verbose. The standard building blocks to such methods are the traits in the num crate from crates.io, most notably Num, Zero and One, and std::cmp::PartialOrd. Numeric literals cannot be generic over any numeric type; they must be done with a trait meth

Categories : Rust

Figuring out lifetime for reference from a consumed value
Can we somehow make the A type carry information about the lifetime of the reference? That is in fact exactly what you are doing when writing enum A<'a> { //' AConst(&'a [u8]) //' } The full type here is A<'a> meaning that A carries inside it a reference of lifetime 'a. To be correct, you need to propagate explicitl

Categories : Rust

What is the difference between Send and 'static on a closure in rust?
Send is a 'kind' http://doc.rust-lang.org/reference.html#built-in-traits send : Able to be sent across task boundaries. 'static is a lifetime that's special: a lifetime that lasts for the entire program. The reference also contains another illuminating section on Send: (we haven't gotten an optimal layout for the reference yet) http://doc.rust-lang.org/reference.html#type-kinds Send : T

Categories : Rust

An instance of different structures as a argument for a function
To create an enum, you'd rather do: enum MyEnum { MySt1(St1), MySt2(St2) } That is, it has two variants, each carrying data of the respective type. Another way to do this if you don't care about which variant you have is to define your own trait and implement it for both: trait Stuff { } impl Stuff for St1 { } impl Stuff for St2 { } fn my_func<T: Stuff>(en: T) { ... } This has

Categories : Rust

How do I collect into an array?
This isn't possible because arrays do not implement any traits. You can only collect into types which implement the FromIterator trait (see the list at the bottom of its docs). This is a language limitation, since it's currently impossible to be generic over the length of an array and the length is part of its type. But, even if it were possible, it's very unlikely that FromIterator would be imp

Categories : Rust

Result<(), &str> or something else
The current state of the art in Rust: an enum to represent the result, bool being the "simplest" one an Option, to encapsulate the result, and give no detail in case of error a Result<R, E> to encapsulate either the result or an error The function you present is a unique challenge, it could be represented either as: Result<(), Error> with Error being whatever you want it to be (&

Categories : Rust

Use macro across module files
You need to add #![macro_escape] at the top of macros.rs and include it using mod macros; as mentioned in the Macros Guide. $ cat macros.rs #![macro_escape] #[macro_export] macro_rules! my_macro { () => { println!("hi"); } } $ cat something.rs #![feature(macro_rules)] mod macros; fn main() { my_macro!(); } $ rustc something.rs $ ./something hi For future reference, $ rustc -v ru

Categories : Rust

Syntax of Rust lifetime specifier
I'm not sure what your exact question is, so I imagine you wanted that code to compile. Check this playpen. Notice that lifetime parameters are part of the type, so you want User<'a> not just User. use std::collections::HashMap; fn main() { struct User<'a> { name: & 'a str } impl <'a>User<'a> { fn new(uname: & 'a str, pwd: & 'a str) -

Categories : Rust

How to compile multiple Rust files into a single C library?
Here, file.rs is your crate root, which is what results in the static library. So to add other files, you have to reference them from the crate root. That is, assuming you have a file other.rs, you could do something like mod other; in file.rs to effectively 'bring in' the contents of other.rs into file.rs. See the guide for more information.

Categories : Rust

In rust how can i do this type conversion in one line
If you look at rust reference you can see that as operator has higher precedence than << so you have to do: fn main () { let num_bits: uint = 32; // just for reference let m: f64 = (1u << num_bits - 2) as f64; println!("mul {}", mul); } You also must specify the bype of 1 as uint (1u) because the compiler cannot deretmine the type for it from the context when written tha

Categories : Rust

Manually call a rust dynamic library
I think the problem stems from the fact that you are casting between incompatible types. Specifically, the dereference *f is going to point to the wrong place. I looked in the Rust code to see how the library is supposed to be used and found an example in src/librustc/plugin/load.rs. I adapted that code to your example: let func = unsafe { // Let this return a `*mut u8`, a very generic pointe

Categories : Rust




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.