Monday, September 29, 2025
HomeGolangGolang Generic Help for strategies outlined on structs - Getting Assist

Golang Generic Help for strategies outlined on structs – Getting Assist


hello Gophers,
I feel this may very well be a beneficial function addition for generics in golang.

kind SomeStruct struct {
	genericValue interface{}
}

Now lets use generics to extract a particular worth kind.
This works completely

func GetGenericReturnValue[T any](enter SomeStruct) (*T, error) {
	if val, okay := enter.genericValue.(T); okay {
		return &val, nil
	}
	return nil, errors.New("invalid")
}
/* Pattern code to exhibit the above use case
	s := SomeStruct{
		genericValue: 42,
	}
	intValue, err := GetGenericReturnValue[int64](s)
	if err != nil {
		fmt.Println("Returned int worth:", *intValue)
	}
*/

However now if I would like the tactic to be related to a struct like under

func (s SomeStruct) GetReturnValue[T any]() (*T,error) {
    if val,okay:=s.genericValue.(T) ;okay{
            return &val,nil
    }
    return &val,errors.New("invalid")
}

It provides a syntax error ==> methodology will need to have no kind parameters

Is there any motive why this above use case shouldn’t be supported?

For individuals questioning what’s distinction between 2 and why I’m making an attempt to advocate second model—> Encapsulation Precept is what I wished to respect

Right here is the reply why it was not applied from the beginning.

https://go.googlesource.com/proposal/+/refs/heads/grasp/design/43651-type-parameters.md#No-parameterized-methods

And right here is the massive dialogue ~3 years, the way it may/needs to be accomplished.

Imho, I see no distinction between sugar like struct methodology and generic func which takes a struct pointer as the primary argument. With present generics implementation, the one factor you are able to do, if you would like “generic” methodology, is to maneuver kind to the struct, as a substitute of func itself, one thing like:

package deal principal

import "fmt"

kind Check[T any] struct {
	genericValue T
}

func (t *Check[T]) GetValue() T {
	return t.genericValue
}

func principal() {
	t := &Check[int]{42}
	fmt.Println(t.GetValue())

	t1 := &Check[string]{"Hiya"}
	fmt.Println(t1.GetValue(), "world!")
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments