Avatar ·

Como adicionar novos métodos a um tipo existente em Go? (por exemplo, a int ou string)

Olá a todos! Comecei a aprender Go depois de Python e C#, e estou com um problema para estender a funcionalidade de tipos embutidos. Em Python, eu costumava fazer assim: ```python # Python - monkey patching class MyInt(int): def is_even(self): return self % 2 == 0 print(MyInt(4).is_even()) # True ``` Em C#, existem extension methods: ```csharp // C# Extension Method public static class IntExtensions { public static bool IsEven(this int value) { return value % 2 == 0; } } ``` Agora estou tentando fazer o mesmo em Go. Quero adicionar um método `IsEven()` ao tipo `int` para verificar se um número é par. Aqui está o que estou tentando: ```go package main import "fmt" // Tentando estender int func (i int) IsEven() bool { return i%2 == 0 } func main() { x := 4 fmt.Println(x.IsEven()) } ``` O compilador dá erro: "cannot define new methods on non-local type int". Entendo que Go é mais rigoroso com tipos, mas como então