Tuesday, 14 January 2025

Golang, Gin: chainable method in Struct

In PHP, a chainable method in a class is one that returns the object itself (typically $this), allowing multiple methods to be called on the same object in a single line, like:

php
class Example { public function method1() { // do something return $this; } public function method2() { // do something else return $this; } } $example = (new Example())->method1()->method2();

In Go (Golang), while Go doesn't have the same concept of classes as in PHP, you can achieve similar behavior using structs and methods that return a pointer to the struct itself. This allows you to chain method calls in a similar way. If you're using the Gin framework, it typically doesn't have a built-in chainable pattern, but you can create chainable methods for your custom structs.

Here’s how you might implement a chainable pattern with Go:

go
package main import "fmt" type Example struct { value int } func (e *Example) Method1() *Example { e.value += 1 return e } func (e *Example) Method2() *Example { e.value *= 2 return e } func main() { e := &Example{} e.Method1().Method2() fmt.Println(e.value) // Output will be 2 (1 + 1, then 2 * 1) }

In this example, each method modifies the Example struct and returns a pointer to the same struct, allowing you to chain calls.

While Gin doesn't inherently encourage chainable methods, you could extend it for custom use cases by applying this pattern in your own code for convenience.

No comments:

Post a Comment

Golang Advanced Interview Q&A