What is the difference between a __weak and a __block reference?

From the docs about __block __block variables live in storage that is shared between the lexical scope of the variable and all blocks and block copies declared or created within the variable’s lexical scope. Thus, the storage will survive the destruction of the stack frame if any copies of the blocks declared within the frame … Read more

Type mismatches resolving a closure that takes arguments by reference

The short version is that there’s a difference between the lifetimes that are inferred if the closure is written inline or stored as a variable. Write the closure inline and remove all the extraneous types: fn test(points: &[Point]) -> (&Point, f32) { let init = points.first().expect(“No initial”); fold(&points, (init, 0.), |(q, max_d), p| { let … Read more

Is it possible to return either a borrowed or owned type in Rust?

Since BigInt implements Clone, you can use a std::borrow::Cow: use num::bigint::BigInt; // 0.2.0 use std::borrow::Cow; fn cal(a: BigInt, b: BigInt, floor: &BigInt) -> Cow<BigInt> { let c: BigInt = a – b; if c.ge(floor) { Cow::Owned(c) } else { Cow::Borrowed(floor) } } Later, you can use Cow::into_owned() to get a owned version of BigInt, or … Read more

Convert Vec into a slice of &str in Rust?

You can create a function that accepts both &[String] and &[&str] using the AsRef trait: fn test<T: AsRef<str>>(inp: &[T]) { for x in inp { print!(“{} “, x.as_ref()) } println!(“”); } fn main() { let vref = vec![“Hello”, “world!”]; let vown = vec![“May the Force”.to_owned(), “be with you.”.to_owned()]; test(&vref); test(&vown); }

Is there an owned version of String::chars?

std::vec::IntoIter is an owned version of every iterator, in a sense. use std::vec::IntoIter; struct Chunks { remaining: IntoIter<char>, } impl Chunks { fn new(s: String) -> Self { Chunks { remaining: s.chars().collect::<Vec<_>>().into_iter(), } } } Playground link Downside is additional allocation and a space overhead, but I am not aware of the iterator for your … Read more

Does println! borrow or own the variable?

The macros print!, println!, eprint!, eprintln!, write!, writeln! and format! are a special case and implicitly take a reference to any arguments to be formatted. These macros do not behave as normal functions and macros do for reasons of convenience; the fact that they take references silently is part of that difference. fn main() { … Read more