Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid receiver type []T ([]T is an unnamed type) workaround?

Tags:

go

I would like to define a method on []T, where T is a type I defined.
It looks like i have to define a new type to do this, but that stops me from using all the builtin functions for slices on this new type (such as len).

Is the go way of doing this to just make ordinary functions, rather than methods? (Kinda like how append() could be a method, but isn't?)

like image 227
Filip Haglund Avatar asked Oct 23 '14 11:10

Filip Haglund


1 Answers

You can define a slice type:

type MySliceType []SomeType
  • You can still use append and slicing operations on values of MySliceType.
  • You can define methods on MySliceType.

You can't, however, monkeypatch []SomeType's methods.

like image 131
thwd Avatar answered Dec 09 '22 20:12

thwd