如何在D中为函数输入按名称的参数? [英] How to enter by-name argument to a function in D?
问题描述
我正在努力通过名称将参数传递给已定义默认参数值的函数:
I am struggling on passing arguments by name to a function that has default parameter values defined:
import std.stdio;
void main() {
void foo(int x=1, int y=2, int z=3) {
writefln("x=%s, y=%s, z=%s", x, y, z);
}
foo(10, 20, 30); // ok, prints: x=10, y=20, z=30
foo(z=30); // Error: undefined identifier 'z'
}
这是一个基本需求。这样的函数可以具有10个或更多的参数,并且可以使用不同的参数集多次调用。每次都列出所有的args简直难以忍受-它需要精确的位置知识,甚至在我的新版本应用程序中可能会发生变化。或者我的应用程序的新版本可以更改默认值,那么我将必须检查所有源代码才能对其进行更改。
This is quite a basic need. Such a function can have 10 parameters or more and might be called multiple times with different set of arguments. It would be unbearable to list all the args everytime - it would require precise knowledge of positions that can even change in a new versions of my app. Or new version of my app can change default value a I would have to go through all my source code to change it.
我认为基本的东西必须使用像D这样的全面语言。
I think so basic thing must be in such a comprehensive language like D.
推荐答案
D没有该功能。有讨论,但我怀疑它是否会命名参数...
D does not have that feature. There were discussions about it but I doubt it will ever have named parameters...
您要求的是基本的东西还是有争议的。我属于认为命名参数只是导致复杂代码的开发人员。 Python是一个很好的例子。我看到函数带有20个命名参数,因为多年来,开发人员一直在不断将它们添加到函数中,这变得一团糟...
It is debatable whether what you ask for is a "basic thing" or not. I am in the group of developers who think named parameters are just leading to complex code. Python is perfect example of that. I have seen functions taking 20 named parameters because over the years developers just kept adding them to the function which became a total mess...
当您拥有10个函数时参数,那么您的设计很可能是错误的。
When you have a function with 10 parameters, then your design is most likely to be wrong.
最后,命名参数会带来额外的开销并影响性能。这是C#界的一篇有趣的文章: http://www.dotnetperls.com/named-parameters 。
Finally, named parameters introduce extra overhead and affect performance. Here is an interesting article from the C# world: http://www.dotnetperls.com/named-parameters .
这篇关于如何在D中为函数输入按名称的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!