How to add new methods to existing types in Go? (e.g., to int or string)
Hi everyone! I just started learning Go after Python and C#, and I'm having trouble extending the functionality of built-in types.
In Python I used to do this:
```python
# Python - monkey patching
class MyInt(int):
def is_even(self):
return self % 2 == 0
print(MyInt(4).is_even()) # True
```
In C# there are extension methods:
```csharp
// C# Extension Method
public static class IntExtensions
{
public static bool IsEven(this int value)
{
return value % 2 == 0;
}
}
```
Now I'm trying to do the same in Go. I want to add an `IsEven()` method to the `int` type to check if a number is even. Here's what I'm trying:
```go
package main
import "fmt"
// Trying to extend int
func (i int) IsEven() bool {
return i%2 == 0
}
```
No answers yet.
Log in to leave an answer
Blogs