Rewrite generics parameter of Self?

Suppose we have Struct<'a> and we want to generate a Struct<'b>, we have to hard code the full name of Struct, if we decided to change the name of Struct, we should change it in its impl block

Could we provide some method like Self<'b>, which allow us change the generics of Self type?

struct Struct<'a>(&'a i32);
impl<'a> Struct<'a>{
//    fn my_clone<'b>(self)->Struct<'b> where 'a:'b{Struct::<'b>(self.0)} // current way
    fn my_clone<'b>(self)->Self<'b> where 'a:'b{Self::<'b>(self.0)} // is it possible not use the name of Struct here?

Self never takes parameters. You could use a (custom) type alias (and change it one extra place instead of many).

1 Like

type alias could be a choice

but, why we couldn't use the self keyword directly?

Is there any disadvantage? or just no one complain about it?

Self is an alias for one type exactly (in a given context). We'd need variadic generics or default and omittable type alias parameters or the like to support both on Self / any single name.

I got your idea, but technically, couldn't we accept Self<parameters> as the real signature and Self is a syntax sugar for Self<parameters>?

Similar trait could be done with aliases:

type Alias<'a> = Struct<'a>;
// Alias<'b> == Struct<'b>
// Alias == Alias<'a> == Struct<'a>

That would be default type parameters, but those don't work with lifetime parameters. Instead, when you elide lifetime parameters on a type constructor, they are inferred:

impl<'a> Struct<'a> {
    fn new(i: &i32) -> Struct { // aka Struct<'_> aka matches that of `i`
    fn zero(_ignored: &i32) -> Self { // aka Struct<'a>

If Self was a type constructor, people would very understandably expect it to work like omitted lifetime parameters. But some lifetime default would have to override the inference so that this code continues to work. That alone is probably a blocker for the feature... unless we first get rid of elided lifetimes in paths (so you have to write Struct<'_>) and then add defaulted life parameters over a series of editions or the like.

Self is special in other ways that would also need consideration (e.g. is this an expansion of receiver types to anything the Self type constructor can construct)?

1 Like

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.