Is there any difference between functions new1 and new2? I am assuming it would matter if arg was &self? Is there any case where one if preferred over the other?
Yes thats true. A simple 'b: 'a would fix the issue when the return is Self. Even though I am not understanding what it means. How does the lifetime defined on the struct affect the method implementations?
What would be the difference between
fn new1(arg: &'a self)
and
fn new2<'b>(arg: &'b self)
how different would these functions behave? When should one opt one over the other?
The first one constrains the lifetime of the borrow to match the lifetime of the struct. Now, due to covariance, this isn't a big deal; when this function is called, the lifetime of the struct can easily be shortened to match the lifetime of the borrow.
&mut T is invariant in T, so the compiler can't shrink this lifetime when you call this function. As a result, any attempt to call new1_mut will force the Name to be mutably borrowed for the entire rest of the time that it exists. (making it impossible to borrow the Name again)
fn main() {
let mut name = Name { arg: b"hello" };
func1_mut(&mut name);
func2(&name); // ERROR: already mutably borrowed.
}
By the way, that's incorrect usage because you're saying arg: &'a self while what you meant was arg: &'a Self. Self is this type (As in the type you're implementing a trait on or implementing methods on) while self is sugar for saying "this is called with an owned argument of type Self and is named self and is therefore a method"