spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » RUST » Page 1
Rust swap struct field
Use std::mem::swap(). let a: &mut A = rw_lock_on_a.write().deref_mut(); let mut my_local_var = SomeType::new(); mem::swap(&mut a.field, &mut my_local_var);

Categories : Rust

missing lifetime specifier [E0106] on function signature
A long time ago, when a function returned a borrowed pointer, the compiler inferred the 'static lifetime, so fn2 would compile successfully. Since then, lifetime elision has been implemented. Lifetime elision is a process where the compiler will automatically link the lifetime of an input parameter to the lifetime of the output value without having to explicitly name it. For example, fn1, without

Categories : Rust

Delegating the creation of data structures
It is not possible to implement a working each_line_in_file_with_path function — at least, not without adding some overhead and unsafe code. Let's look at the values involved and their types. First is path, of type Path (either posix::Path or windows::Path). The constructors for these types receive a BytesContainer by value, therefore they take ownership of it. No issues here. Next is file

Categories : Rust

How to make a struct where one of the fields refers to another field
I think you're right in that it's not possible to do this without unsafe code. I would consider the following two options: Change the reference in Bar to an index. The contents of the box won't be protected by a borrow, so the index might become invalid if you're not careful. However, an index might convey the meaning of the reference in a clearer way. Move Box<[u8]> into Bar, and add a fu

Categories : Rust

multiple matching crates for `time` but there're no versions specified
The crate time has recently been move to an external repository, but you currently still have the old crate bundled with rustc, as it is currently kept as deprecated. Thus you have two crates "libtime", and rustc doesn't know which take. As you're using cargo, the fix is simple: add libtime in your dependencies by putting this in your Cargo.toml, cargo will tell rusctc which libtime it should us

Categories : Rust

Access newtype in Rust
There are one-and-a-half (soon to be two) ways: #![feature(tuple_indexing)] struct Foo([int, ..5]); fn main() { let foo = Foo([1,2,3,4,5]); let Foo([_, foo_1, ..]) = foo; let foo_3 = foo.0[3]; println!("[_, {}, _, {}, _]", foo_1, foo_3); } Specifically, tuple_indexing is likely to be un-gated soon, so you won't need the feature attribute to use it. Basically, Foo is a tuple

Categories : Rust

Comparing slices and lifetimes
User Sharp helped me out on IRC. I changed the snippet to let data: [u8, ..4] = [0x12, 0x34, 0x56, 0x78]; as_bytes(&data, |bytes| { assert_eq!(bytes, [[0x12, 0x34, 0x56, 0x78].as_slice()].as_slice()); }); Which compiles and indeed compares the contents of the slices. As to why exactly the error was triggered, I'm still not quite sure.

Categories : Rust

Trouble porting C++ code to Rust
See This One Weird Trick To Beat The Borrow Checker: Compilers Hate It. #[deriving(Eq, PartialEq, Show, Clone)] struct Trie { eow: bool, val: char, chd: Vec<Trie> } impl Trie { fn new(eow: bool, val: char, chd: Vec<Trie>) -> Trie { Trie{eow: eow, val: val, chd: chd} } fn push_word(&mut self, word: &String) { let mut trie = self;

Categories : Rust

rust create a String from file.read_to_end()
Check the functions provided by the io::Reader trait: http://doc.rust-lang.org/std/io/trait.Reader.html read_to_end() returns IoResult<Vec<u8>>, read_to_string() returns IoResult<String>. IoResult<String> is just a handy way to write Result<String, IoError>: http://doc.rust-lang.org/std/io/type.IoResult.html You can extract Strings from a Result either using unwrap

Categories : Rust

Only show first screenful of compile errors in Rust when building with Cargo?
cargo test writes errors to stderr, so you have to redirect stderr to stdout like this: cargo test 2>&1 | less

Categories : Rust

Are rust matching statements exectued in order & can overlap?
Yes the match statements are guarantied to be executed in order, so basically these two matches are equivalent : match (a,b) { (true, _) => println!("first is true !"), (_, true) => println!("second is true !"), (_, _) => println!("none is true !"), } match (a,b) { (true, _) => println!("first is true !"), (false, true) => println!("second is true !"), (fal

Categories : Rust

Parametric mutability
There is no parametric mutability. I know that several people have expressed a strong desire for something along those lines, but I'm not aware of any actual plans as yet. There is also no generic value parameters. I believe the core team definitely wants it, but it's not a priority right now.

Categories : Rust

Is it neccesary to cast to float to access basic math funcitons in rust
No. As a quick search of the API reference reveals, you can just use std::cmp::min: use std::cmp::min; fn main() { let a = 1i; let b = 2i; let smallest = min(a, b); println!("{}", smallest); } min being declared specially on FloatMath is... well, I have no idea. Possibly an oversight during the recent numeric traits overhaul because floating point types do not implement Ord, due to

Categories : Rust

Rust modify item during iteration in BinaryHeap
RefCell from (cell module) is probably something you should explore, it trumps the compile-time guarantees of ownership by inserting run-time guarantees instead. So, if you have a generic Key and Value, you would create such a structure for BinaryHeap: struct PartiallyMutable<Key, Value> { key: Key, value: RefCell<Value>, } impl<Key, Value> Eq for PartiallyMutable<K

Categories : Rust

In rust concatenating bytes, strings and comparison
I’d use &'static [u8]: pub const CRLF: &'static [u8] = b" "; // or &[CR, LF] I would also say that you should be careful about the line types that you’re using; is cur_line guaranteed to be UTF-8? If not, it should be Vec<u8> rather than String, and CRLF should potentially be &'static str, " ". But anyway, the comparison cur_line.as_bytes() == CRLF is fine. (Once it

Categories : Rust

Updating registry `https://example.com/`
I'm not sure why you're being downvoted. You may just have an older Cargo, when the registry was set to example.com. When did you last install it? See also: this reddit thread http://www.reddit.com/r/rust/comments/2mywa1/cargo_update_error_on_registry_httpsexamplecom/

Categories : Rust

inspect rust traits at runtime
There is no facility for doing this at runtime; at compile time, however, there is, and this is what rustdoc does. With that you can see things like the core::str::StrSplits documentation which covers the information you requested.

Categories : Rust

Scope of addresses: Does not live long enough
I think this happens because of different rules for & operator when it is used in bindings or elsewhere. This: let y: &int = &31i; is equivalent to this: let temp: int = 31i; let y: &int = &temp; except that temp is invisible. This is explained e.g. in lifetimes guide, though this guide seems to be the older version which has not been rewritten yet (like other guides).

Categories : Rust

Convert a String to int in Rust?
With a recent nightly, you can do this: let my_int = from_str::<int>(&*my_string); What's happening here is that String can now be dereferenced into a str. However, the function wants an &str, so we have to borrow again. For reference, I believe this particular pattern (&*) is called "cross-borrowing".

Categories : Rust

How to debug a crate in rust
Your question is a bit fuzzy, so I'll describe what I did: Create a new crate: cargo new so cd so/ Add a small bit of code: // src/lib.rs fn thing1(a: int) -> int { a + 2 } fn thing2(a: int) -> int { a * a } pub fn do_a_thing(a: int, b: int) -> int { thing2(b) - thing1(a) } Created an external test; one that lives in tests. This matches your comment about test_XXX, a

Categories : Rust

Rust htons and ntohs
You can use the from_be and to_be functions on the Int trait. Network order is big endian, so this is equivalent. You can find example usages in the documentation for them: http://doc.rust-lang.org/core/num/trait.Int.html#method.to_be http://doc.rust-lang.org/core/num/trait.Int.html#method.from_be

Categories : Rust

How to mutate struct field in method
You need to use &mut self instead of &self: struct Point { x: int, y: int, } impl Point { fn up(&mut self) { self.y += 1; } } fn main() { let mut p = Point { x: 0, y: 0 }; p.up(); } Rust mutability is inherited; it means that the owner of the data decides if the value is mutable or not. References, however, do not imply ownership and hence they can

Categories : Rust

Store value in struct through trait
The problem is, as the error message says, that the trait TraitToImpl is not object safe. That is, it is not safe to use that particular trait through a reference (i.e. &TraitToImpl or Box<TraitToImpl>. Specifically, the dosomethn method takes self by value. Consider: how does the compiler call this method on a Cont that's been placed in a Box<TraitToImpl>? It has to copy the v

Categories : Rust

Rust error trait weird method missing
You must add the following line either at the top of the source file or inside main to bring the Error trait's method in scope: use std::error::Error; You can now also call the trait method as if it was a static function, which doesn't require adding the above line: fn main() { let e = O; println!("Hello, world!{}", error::Error::description(&e)) }

Categories : Rust

rust-crypto giving many unresolved import errors
A very recent breaking change made enums namespaced within their parent types. They haven't yet merged the pull request to fix that (Travis was showing the result of that PR)

Categories : Rust

How can I make a structure with internal references?
It is not possible to represent this concept in Rust with just references due to Rust’s memory safety—such an object could not be constructed without already existing. As long as nodes and adjacencies are stored separately, it’s OK, but as soon as you try to join them inside the same structure, it can’t be made to work thus. The alternatives are using reference counting (Rc<T> if im

Categories : Rust


Recently Add
Strange Rust compilation error
Rust swap struct field
missing lifetime specifier [E0106] on function signature
Delegating the creation of data structures
How to make a struct where one of the fields refers to another field
multiple matching crates for `time` but there're no versions specified
Access newtype in Rust
Comparing slices and lifetimes
Trouble porting C++ code to Rust
rust create a String from file.read_to_end()
Only show first screenful of compile errors in Rust when building with Cargo?
Are rust matching statements exectued in order & can overlap?
Parametric mutability
Is it neccesary to cast to float to access basic math funcitons in rust
Rust modify item during iteration in BinaryHeap
In rust concatenating bytes, strings and comparison
Updating registry `https://example.com/`
inspect rust traits at runtime
Scope of addresses: Does not live long enough
Convert a String to int in Rust?
How to debug a crate in rust
Rust htons and ntohs
How to mutate struct field in method
Store value in struct through trait
Rust error trait weird method missing
rust-crypto giving many unresolved import errors
How can I make a structure with internal references?
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.