What are caller and callee?

Following is my code:

trait Get<'a> {}

struct Foo;
impl<'a> Get<'a> for Foo {}

fn caller_func<'a, T>(get: T)
where
    T: Get<'a>,
{}

fn callee_func<T>(get: T)
where
    for<'a> T: Get<'a>,
{}

When I call caller_func(Foo), what does that mean by: the caller choose the lifetime.
When I call callee_func(Foo), what does that mean by: the callee choose the lifetime.

What is the question exactly?

fn caller_func<'a, T>(get: T)
where
    T: Get<'a>,
{}

In caller_func, the caller chooses the lifetime 'a and a type T, and the caller must ensure that T implements Get<'a> for the chosen lifetime 'a.

fn callee_func<T>(get: T)
where
    for<'a> T: Get<'a>,
{}

Here, the caller chooses a type T, but that type T must implement Get<'a> for any lifetime 'a (e.g. for very short lifetimes but also for 'static).

1 Like

Thanks for your help.

What is the caller? Is it just the function caller_func or is it some scope that is calling the function caller_func?

Given the two functions

fn f() {
    g();
}

fn g() {}

f is the "caller" (the one doing the call) in their relationship, and g is the "callee" (the one being called).

2 Likes

You're probably familiar with Vec<T>, where you -- the user of Vec<T> -- can choose whatever T you need. A fn with_generics<'lifetime, Type> is similar -- and one who uses it (the caller) can choose whatever 'lifetime and Type they need.

When it comes to lifetimes, it's also important that the caller can only choose lifetimes that are at least as long as the call -- the function body can assume the lifetime is valid for the entire body (longer than any local, which all drop by the end of the function body). It's important because it means the lifetime can't be smaller than the function body -- so inside the function, it's not possible to borrow a local for the generic lifetime.


You didn't ask about this part, but in anticipation:

// Caller can pass in any implementor of Display
fn foo(d: impl Display)

is analogous to

// Caller chooses D (provided D implements Display)
fn foo<D: Display>(d: D)

While

// Function decides the single (but opaque) type that is returned
fn foo() -> impl Display

is analogous to

// Function decides the single type that is returned
fn foo() -> String
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.