Generic receiver or something like that

I have 3 structs in one application. Those are

type LoginResponse struct {
ResultResponse
Token string json:"Token"
ComercioId string json:"ComercioId"
UsuarioId string json:"UsuarioId"
}

type DepositoPagoResponse struct {
ResultResponse
TransaccionID int json:"TransaccionId"
Producto string json:"Producto"
FechaTransaccion time.Time json:"FechaTransaccion"
MontoTransaccion float64 json:"MontoTransaccion"
}

type VerifyAccountResponse struct {
ResultResponse
Producto string json:"Producto"
Saldo float64 json:"Saldo"
}

type ResultResponse struct {
IsSuccess bool json:"IsSuccess"
Codigo int json:"Codigo"
Mensaje string json:"Mensaje"
}

To set properties in my structs i wrote methods that works like builder pattern. For example

func (r *VerifyAccountResponse) WithSuccess(success bool) *VerifyAccountResponse {
r.IsSuccess = success
return r
}

func (r *VerifyAccountResponse) WithCodigo(codigo int) *VerifyAccountResponse {
codigo, mensaje := GetCodeMessage(codigo)
r.Codigo = codigo
r.Mensaje = mensaje
return r
}

So i wrote soemthing like
r := &LoginResponse{}
r.WithSuccess(true).WithCode(100).WithToken(“123”) and so on. The methods WithSuccess and WithCode are repeated by each struct.
I would like to wrote those methods only one time for the ResultResponse in each parent struct.
I thinking something like a generic function receiver or something like that to avoid wrote those methods for each parent struct.
Is it possible ? If so, please some hints would be useful…

TIA,
Yamil

I got an easy way to make my code simpler. First, i wrote a function that creates a ResultResponse object and then add a WithResultResponse to each other structs. Something like
response.WithResultResponse(models.BuildResultResponse(true, 1097)).
WithToken(“abc123”).
WithUsuarioId(“usuario_1”).
WithComercioId(“9999”)

What’s the problem with writing:

r := LoginResponse{
	ResultResponse: ResultResponse{
		IsSuccess: true,
		Codigo:    100,
	},
	Token: "123",
}

It’s no a problem just want to know how to deal with generics and receivers.

Thanks!!!

Go doesn’t let you write generic builder methods tied to embedded structs like ResultResponse, so you have to repeat methods for each parent type if you want to keep chaining (WithSuccess, WithCodigo, etc.). To reduce duplication, you can move the shared logic into helper functions and call those from each struct’s builder methods. It’s cleaner, even if not fully DRY. Generics or interfaces won’t help much here unless you go deep into advanced patterns, which may not be worth the complexity.

That what I did… Thanks a lot !!!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.