Friday, May 17, 2024
HomeGolangGenerics - is there an equal to Rust "Self" kind - Getting...

Generics – is there an equal to Rust “Self” kind – Getting Assist


Rust generic has a “Self” which is the Concrete kind of the instantiated Generic kind. Is there an equal in Go?

Particularly, so i can get Clone() to return a Self. Then i can have generic struct which can implement the Clone interface.

One thing like,

kind Cloner[T any] interface {
    Clone() T
}

kind Guardian[T any] struct {
    parentAttr T
    Cloner[Self] 
}

func (p Guardian[T]) Clone() Guardian[T] {  return a clone of the mum or dad obj }

kind Baby[T any] struct {
   Guardian[T]
   childAttr string
}

func (c Baby[T]) Clone() Baby[T] { return a clone of the kid obj }

Hello @globalflea,

It’s certainly attainable that an interface technique’s argument refers back to the interface kind – see this text for particulars:

The right way to use generics for creating self-referring interfaces

TL;DR:

Step 1. The Cloner interface stays unchanged.

kind Cloner[C any] interface {
	Clone() C
}

C is just not restricted to something but, however step 2 takes care of this.

Step 2. A operate that clones any kind makes use of Cloner[T] as kind restriction:

func CloneAny[T Cloner[T]](c T) T {
	return c.Clone()
}

Then, for any variable s whose kind implements Cloner, you possibly can merely name

CloneAny(s)

to clone s.

Playground hyperlink

The weblog article explains this resolution in additional element.

1 Like

Hello Christoph,

thanks on your weblog publish.

You utilize this snippet within the publish:

cloned := CloneAny(s)
if cs, okay := cloned.(CloneableSlice); okay {
    fmt.Println(cs[3])
}

Why not use cloned := s.Clone() and make each Clone-method return the actual kind?

Then you definately don’t want a kind assertion.

Hello @guettli,

As a result of then the Clone strategies wouldn’t implement the Cloner interface.

Your resolution is after all completely nice if a Cloner interface is just not required. All the time use the best resolution attainable!

This subject was mechanically closed 90 days after the final reply. New replies are not allowed.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments