如何通过扩展类型向基本类型(如int)添加功能?

I would love to be able to add methods to an existing type like int for instance:

func (i *int) myfunction {
   ...
}

However, this obviously produces an error.

cannot define new methods on non-local type

The top google result is a github issue opened against golang for this very thing. Promisingly, the answer is that you can already get this functionality another way so they will not make this change to the language.

Unhelpfully, the response is vague

type extended Existing

and it does not explicitly show how to implement what OP was asking for, which was:

func (a int) sum(b int) (total int) {
    total = a + b
    return
}

So, how does one extend an int to add functionality? Can it still be used like an int? If so, how?

I would like to effectively have something that behaves in all ways as an int, but has additional methods. I would like to be able to use this in place of an int in all ways by some means.

I would like to effectively have something that behaves in all ways as an int, but has additional methods. I would like to be able to use this in place of an int in all ways by some means.

This is not possible currently in Go since it doesn't support any kind of generics.

The best you can achieve is something like the following:

package main

type Integer int

func (i Integer) Add(x Integer) Integer {
    return Integer(int(i) + int(x))
}
func AddInt(x, y int) int {
    return x + y
}

func main() {
    x := Integer(1)
    y := Integer(2)
    z := 3

    x.Add(y)
    x.Add(Integer(z))
    x.Add(Integer(9))

    # But this will not compile
    x.Add(3)

    # You can convert back to int
    AddInt(int(x), int(y))
}

You can declare a new type based on int, and use that:

type newint int

func (n newint) f() {}

func intFunc(i int) {}

func main() {
   var i, j newint

    i = 1
    j = 2
    a := i+j  // a is of type newint
    i.f()
    intFunc(int(i)) // You have to convert to int
}