Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Idea: Types of Closures #60

Open
harudagondi opened this issue Sep 30, 2022 · 0 comments
Open

Idea: Types of Closures #60

harudagondi opened this issue Sep 30, 2022 · 0 comments

Comments

@harudagondi
Copy link

harudagondi commented Sep 30, 2022

use std::any::Any;

fn f<T, U>(t: T, u: U)
where
    T: 'static,
    U: 'static,
{
    if t.type_id() == u.type_id() {
        print!("1")
    } else {
        print!("0")
    }
}

fn c() -> impl Fn() {
    || {}
}

fn main() {
    f(|| {}, || {});
    f(c(), c());
}

Answer: 01

Hint

Do closures have the same type? How many types can a function return?

Explanation

According to the Rust Reference Book, "A closure expression produces a closure value with a unique, anonymous type that cannot be written out."

However, functions must always return one singular type, and as such all || {} produced by new_closure() must be of the same type.

Personally this surprised me because I originally thought that all closures are unique from each other, but this assumption can be broken by returning closures from functions (or even closures!).

Another fun exercise:

use std::any::Any;

fn f<T, U>(t: T, u: U)
where
    T: 'static,
    U: 'static,
{
    match t.type_id() == u.type_id() {
        true => print!("1"),
        false => print!("0"),
    }
}

fn eq<T: PartialEq>(t0: T, t1: T) {
    match t0 == t1 {
        true => print!("1"),
        false => print!("0"),
    }
}

fn c() -> impl Fn() {
    || {}
}

fn d(x: i32) -> impl Fn() -> i32 {
    move || x
}

fn main() {
    let x = d(1);
    let y = d(2);

    let a = x();
    let b = y();

    f(|| {}, || {});
    f(c(), c());
    f(x, y);
    eq((|| {})(), (|| {})());
    eq(c()(), c()());
    eq(a, b);
}

Answer: 011110

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant