Of &'static fn pointers and trait method pointers


#1

Ok so i know that functions are actually function pointers, and they are 'static.

are trait methods the same?

e.g

trait Trait {
    fn method(&self);
}

struct Struct;

impl Trait for Struct {
   fn method(&self) {}
}

fn main() {
    let var = Struct;
    var.method(); // is var.method a &'static pointer?
}

It seems logical that var.method is also &'static but i wanted to be sure.
so here i am asking.


#2

var.method isn’t anything. What I mean is, it’s not a value or an expression. You can’t not call an instance method like that.

Now, Struct::method is a fn(&Struct) function pointer.


#3

so does that mean that it is &'static?


#4

Struct::method is indeed a function pointer, you just have to be aware that you must supply var as the first argument.

trait Trait {
    fn method(&self);
}

struct Struct;

impl Trait for Struct {
    fn method(&self) {}
}

fn takes_pointer(f: fn(&Struct)) {
    let var = Struct;
    f(&var)
}

fn main() {
    takes_pointer(Struct::method);
}

#5

thanks for this


#6

Function pointers don’t have explicit lifetimes at all, but if you’re asking “does the function pointer point to something that exists forever”, then yes.


#7

thanks as well.