Extension methods in D?
Hey folks, I'm trying to get these bits of syntax to make sense to me:
S[] split(S)(S s) if (isSomeString!S)
{
...
}
and
string join(in string[] words, string sep)
{
...
}
(As see开发者_开发技巧n in phobos/src/std/string.d
)
As far as I can tell, this is the piece of code that lets us do stuff like:
string[] parts = "/foo/bar/baz".split("/"); // string[] {"foo", "bar", "baz"}
string part = parts.join("-"); // string "foo-bar-baz"
Which basically makes me believe something like the extension methods I know from CSharp are possible in d. The problems I have are:
- That I'm not 100% sure i'm looking at the right function declarations here
- That I don't see what makes them similar.
They're not extension methods per-se, just some bug that turned into a neat feature.
The similarity between those two methods is that both has a string as the first parameter. So the trick that is at work here, is that given an array T[] arr, and a function
U foo (T[] t, other params)
can be called by doing
arr.foo(some arguments matching other params)
In D, any function which takes an array as its first argument can be called as if it were a member function of that array. And since strings are arrays, that would include strings. So, something like
T[] replace(in T[] array, in T[] from, in T[] to)
can be called two different ways:
auto replacedStr1 = replace("hello world", "hello", "goodbye");
auto replacedStr2 = "hello world".replace("hello", "goodbye");
This feature currently only works for arrays (IIRC, it came about due to a bug that allowed it, and it was decided that it was actually nice to have, so it was actually made a part of the language), but supposedly, at some point, it will be made to work for all types. Having it work for all types is called uniform function call syntax. With that implemented, you'd be able to do stuff like
auto bigger = 2.max(5);
But as uniform function call syntax has not been implemented yet, you can only do that sort of thing with arrays. It's quite common for people to program that way with strings rather than passing them as the first argument to a function.
精彩评论