9 ms·
So, I think the key thing here is unboxed. You can write methods on values whose in-memory representation is the same as an int. It performs in all ways like
by NateDad 12y ago
So, I think the key thing here is unboxed. You can write methods on values whose in-memory representation is the same as an int. It performs in all ways like an int (you can do arithmetic operations on it, etc). It's not boxed, the way other languages would require it to be in order to have methods.
C# extension methods are just syntactic sugar.
public static int WordCount(this String str)
Yes, this means that you can now do this:
string foo = "howdy partner!"
int count = foo.WordCount()
Is that really any better than this?
string foo = "howdy partner!"
int words = WordCount(foo)
The only reason this is useful in C# is because it doesn't support bare functions, all methods have to be on an object. In Go, this is not a problem, you can have bare methods.
Also, extension methods, in practice (and I have a lot of practice with them), are a pain in the butt... because they're magic additional methods on a class that only exist if you include the right project... which means if you try to copy some logic, some of the functionality will not compile in the new location until you figure out what projects to include in the new spot. That's still requiring work by the caller, except that it's much less obvious what you need to do to get it to work.
In contrast, Go's type definitions are 100% clear and obvious, and there's never a question where the functionality is coming from. That clarity makes a huge difference when you're trying to understand the code.
Of course, you'd never actually do that for most C# extension methods in Go, it's ridiculous to make a new type just to make it look like you're calling methods on that type. You'd just write a bare function like a normal person:
package count
func Words(s string) int {}
// elsewhere
foo := "Howdy Partner!"
words := count.Words(foo)
- seanmcdirmid 12y agoWhere extension methods really shine is with generic classes and structures, you can define methods over arbitrary generic bindings; e.g. a method over List of int. Of course that isn't a problem in Go. And even then, its all about the intellisense.
- NateDad 12y agoIntellisense is a good point. If you already have the variable there, getting the free "list of stuff I can do with this" can be pretty handy.
- pcwalton 12y agoI don't see what the difference is between having to hunt for the class that implements an extension method and having to hunt for the newtype wrapper. Seems like the same thing. Also, extension methods don't involve any boxing.