logo
down
shadow

Confustion with 'ref' in rust in closures


Confustion with 'ref' in rust in closures

By : user3099384
Date : January 11 2021, 03:32 PM
will be helpful for those in need Taking a look at the docs page for Lines(The iterator adapter for producing lines from a str), we can see that the item produced by it is:
code :
type Item = &'a str;
dbg!(ls.clone().map(|ref l| l[..]).collect::<Vec<&str>>().join("\n"));  # doesn't work
//Can become:
let temp = ls
    .clone()
    .map(|ref l| l[..])
    .collect::<Vec<&str>>()
    .join("\n");
println!("{}", temp);
fn foo(ref x: String) {}
let y: fn(String) = foo;
fn foo(x: String) {
   let x: &String = &x;
}
let x = 2;
let y = &x;
let &z = y; //Ok, we're moving a `Copy` type


Share : facebook icon twitter icon
Passing around and evaluating rust closures

Passing around and evaluating rust closures


By : Senthil
Date : March 29 2020, 07:55 AM
may help you . There are two problems: one is a bug in Rust, the other is actually a problem with your code.
The bug in Rust is inference with closures is (currently) horrible, one has to give them explicit types when one wants anything other than &fn. (One filing of this is #2190.)
code :
pub fn flat_map<T, U>(v: &[T], f: &fn(t: &T) -> ~[U]) -> ~[U]
fn main() {
  let list = get_list();
  let res = list.flat_map(|f| (*f)());
  println(res.to_str());
}

fn get_list() -> ~[~fn() -> ~[~str]] {
    let f1: ~fn() -> ~[~str] = || ~[~"foo"];
    let f2: ~fn() -> ~[~str] = || ~[~"bar"];

    ~[f1, f2]
}
Calling closures from an array in Rust

Calling closures from an array in Rust


By : Kone Tidiane Youssep
Date : March 29 2020, 07:55 AM
will be helpful for those in need The .iter() method of vector yields immutable references, you need mutable ones to call the closure, thus you should use .iter_mut() :
code :
fn main() {
    let mut closures = [|x: int| x * x, |x| x + 1];
    for closure in closures.iter_mut() {
        println!("{}", (*closure)(10i));
    }
}

-----

100
11
Struggling with closures and lifetimes in Rust

Struggling with closures and lifetimes in Rust


By : user5141720
Date : March 29 2020, 07:55 AM
help you fix your problem
I think that is a function that accepts a closure (that itself accepts a pair and returns unit) and a pair and returns unit. I seem to have to double bracket things: is that correct?
code :
use std::collections::HashSet;

fn iterNeighbors<F>(mut f: F, (i, j): (i32, i32)) -> ()
where
    F: FnMut((i32, i32)) -> (),
{
    f((i - 1, j));
    f((i + 1, j));
    f((i, j - 1));
    f((i, j + 1));
}

fn nthLoop(n: i32, s1: HashSet<(i32, i32)>, s2: HashSet<(i32, i32)>) -> HashSet<(i32, i32)> {
    if n == 0 {
        return s1;
    } else {
        let mut s0 = HashSet::new();
        for &p in &s1 {
            let add = |p| {
                if !(s1.contains(&p) || s2.contains(&p)) {
                    s0.insert(p);
                }
            };
            iterNeighbors(add, p);
        }
        drop(s2);
        return nthLoop(n - 1, s0, s1);
    }
}

fn nth(n: i32, p: (i32, i32)) -> HashSet<(i32, i32)> {
    let mut s1 = HashSet::new();
    s1.insert(p);
    let s2 = HashSet::new();
    return nthLoop(n, s1, s2);
}

fn main() {
    let s = nth(2000, (0, 0));
    println!("{}", s.len());
}
Rust closures from factory functions

Rust closures from factory functions


By : Birgül
Date : March 29 2020, 07:55 AM
should help you out The error says that names must outlive the static lifetime, this is because the boxed Fn has static lifetime. You have two options:
code :
fn printer(names: Vec<&'static str>) -> Box<Fn() -> String>{
    Box::new(move|| {
        // ...
    })
}
fn printer<'a>(names: Vec<&'a str>) -> Box<Fn() -> String + 'a>{
    Box::new(move|| {
        // ...
    })
}
fn main() {
    let names = vec!["foo", "bar", "baz"];
    let print = printer(&names);
    let result = print();
    println!("{}", result);
    do_other_thing(names.as_slice());
}

fn printer<'a>(names: &'a Vec<&str>) -> Box<Fn() -> String + 'a>{
    Box::new(move || {
        // this is more idiomatic
        // map transforms &&str to &str
        names.iter().map(|s| *s).collect()
    })
}
Closures as a type in a Rust struct

Closures as a type in a Rust struct


By : DannyBTZ
Date : March 29 2020, 07:55 AM
will be helpful for those in need Struct::new doesn't have any parameter that depends on F, so the compiler is unable to infer what type it should use for F. If you called a method later that used F, then the compiler would use that information to figure out the Struct's concrete type. For example:
code :
use std::hash::Hash;
use std::collections::HashMap;

pub struct Struct<T, F>
    where T: Eq,
          T: Hash,
          F: Fn() -> T,
{
    hash_map: HashMap<T, F>,
    value: T,
}

impl<T, F> Struct<T, F>
    where T: Eq,
          T: Hash,
          F: Fn() -> T,
{
    pub fn new(init_value: T) -> Struct<T, F> {
        Struct {
            hash_map: HashMap::new(),
            value: init_value,
        }
    }

    pub fn set_fn(&mut self, value: T, func: F) {
        self.hash_map.insert(value, func);
    }
}

fn main() {
    let mut a = Struct::new(0);
    a.set_fn(0, || 1); // the closure here provides the type for `F`
}
fn main() {
    let mut a = Struct::new(0);
    a.set_fn(0, || 1);
    a.set_fn(1, || 2);
}
error[E0308]: mismatched types
  --> <anon>:33:17
   |
33 |     a.set_fn(1, || 2);
   |                 ^^^^ expected closure, found a different closure
   |
   = note: expected type `[closure@<anon>:32:17: 32:21]`
   = note:    found type `[closure@<anon>:33:17: 33:21]`
note: no two closures, even if identical, have the same type
  --> <anon>:33:17
   |
33 |     a.set_fn(1, || 2);
   |                 ^^^^
help: consider boxing your closure and/or using it as a trait object
  --> <anon>:33:17
   |
33 |     a.set_fn(1, || 2);
   |                 ^^^^
pub struct Struct<T>
    where T: Eq,
          T: Hash,
{
    hash_map: HashMap<T, Box<Fn() -> T + 'static>>,
    value: T,
}
pub fn set_fn<F: Fn() -> T + 'static>(&mut self, value: T, func: F) {
    self.hash_map.insert(value, Box::new(func));
}
Related Posts Related Posts :
  • Consistent TypeIds for dynamically loaded crates
  • How to "use another-file" in rust? Module with hyphens in it
  • Rust generic type that can either own or borrow its content
  • Are all macros in the Rust std library included in the prelude?
  • Why don't we need to extract values from Result in some rust iterators?
  • How can I ignore extra tuple items when deserializing with Serde? ("trailing characters" error)
  • Not comparing string in Rust
  • What are best practices for `unsafe` functions in which only a small part of the code is actually doing `unsafe` things?
  • what's the best way to 'borrow' a struct deeply moved into other objects?
  • how to replace member of a structure using this member's method which consume this member itself?
  • "use of undeclared type or module" when using Diesel's `belongs_to` attribute
  • Why is the width ignored for my custom formatter implementation?
  • i need to push (Vec) of a member of struct contained, he is a struct as well
  • How can I invoke a Java method from Rust via JNI?
  • Why doesn't the borrowed value live long enough when created in constructor in lifetime-annotated impl block?
  • Why is it impossible to dereference a boxed iterator trait object?
  • How to build a dependency with a different version of the Rust compiler?
  • How can I display a compiler warning upon function invocation?
  • How can I implement traits for type aliases?
  • What order is `on_initialize` invoked across different modules in a Substrate runtime?
  • Why can't I divide a BigInt with another BigInt and save it to a variable I've initialized with zero?
  • bash: gdb: No such file or directory
  • Where will String::from("") be allocated in a match arm?
  • Rustlings thread exercise, why do I NOT dereference Mutex(Struct)?
  • Why is it not possible to update a value in a HashMap using bracket [ ] notation?
  • How to create a new blockchain project based on CENNZnet?
  • How can I add 1 to a generic T?
  • How to group_by vector's key
  • Why doesn't Rust support overloading function or method?
  • Is "this represents potential undefined behavior in your code" error when using a match arm guard a bug in the
  • How to format a byte into a 2 digit hex string, in Rust
  • How to store a hyper::server::Server as a field in a struct?
  • How do I modify the response body in an actix-web 1.0 middleware?
  • Why does the compiler prevent me from using push on a Vec created using collect()?
  • Is it theoretically possible to specialise trait behaviour?
  • How can I run a set of functions concurrently on a recurring interval without running the same function at the same time
  • Check if Rust is running a test build
  • undefined reference to `printf' in Rust
  • Why doesn't a move closure take ownership of a variable?
  • Is there any compiler flag to force undefined behavior for signed integer overflow?
  • Join iterator of &str
  • Why does "move" in Rust not actually move?
  • What does 0u8 mean in Rust?
  • Where does a variable passed to Reqwest's Result::read_to_string get the data from?
  • How do I use tokio::timer::Timeout with Future::wait?
  • Why does a variable holding the result of Vec::get_mut not need to be mutable?
  • How can I use serde to serialize a struct to another Rust data structure?
  • Serializing a sequence in Serde when both sequence length and types must be known?
  • How can I support an unknown or other value for a Serde enum?
  • How do I use combinators to avoid verbose matching without getting the error "cannot return value referencing funct
  • Will the non-lexical lifetime borrow checker release locks prematurely?
  • Modify a struct while iterating over an Iterable in the struct
  • Does a generic lifetime materialize as the reference's lifetime or the referenced value's lifetime?
  • How do I append to a tuple?
  • What happens to heap allocated value after variable that holds the ownership of that value gets reassigned?
  • Is `cargo clippy` a superset of `cargo check`?
  • Injecting dynamic lib into a thread
  • Mutex can deference struct's but not primitives
  • lifetime bound on associated type is rejected although it seems valid
  • Get the Vec of owned values from a HashMap
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org