如何简单地分配多个 return 值?
How to assign simply multiple return values?
传统上这是使用 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:
中的一个函数来实现
这适用于元组和静态数组。
传统上这是使用 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:
这适用于元组和静态数组。