传统上,这是通过 out
参数完成的,例如:
void notfun(ushort p, out ubyte r0, out ubyte r1)
{
r0 = cast(ubyte)((p >> 8) & 0xFF);
r1 = cast(ubyte)(p & 0xFF);
}
使用元组可以将其重写为
auto fun(ushort p)
{
import std.typecons;
return tuple
(
cast(ubyte)((p >> 8) & 0xFF) ,
cast(ubyte)(p & 0xFF)
);
}
不幸的是,结果不能直接分配给变量元组:
void main(string[] args)
{
ushort p = 0x0102;
ubyte a,b;
// ugly brute cast!
*(cast(ReturnType!(typeof(fun))*) &a) = fun(0x0102) ;
}
是否有特殊的语法来允许类似的事情
(a,b) = fun(0x0102);
或者任何其他惯用的方式来做类似的事情?
最佳答案
可以实现 PHP's list
construct作为 D 中的函数:
这适用于元组和静态数组。
关于tuples - 如何简单地分配多个返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33358247/