我在Rust中有一些返回两个元素的方法,在这些场景中返回两个元素对我来说真的很有意义。虽然,当实际调用这些方法时,我注意到Rust不允许使用元组作为左值,所以我无法重新分配它们。假设test()
是一个返回两个值的方法,我最终写了很多看起来像这样的代码:
let (mut val1, mut val2) = test();
for i in 0..100 {
// partially removed for brevity;
let (_val1, _val2) = test();
val1 = _val1;
val2 = _val2;
}
let (_val1, _val2) = test();
val1 = _val1;
val2 = _val2;
通常,从我的方法返回的两个值是一些结构,反过来它们也有一些方法,所以我想调用那些返回结构中的方法。无论如何,我经常使用上面的模式,它变得很快很麻烦。有没有更好的方法来做我想要的Rust?
答案 0 :(得分:1)
您可以创建一个宏
Assuming a file called `filename.json` contains the following lines
{"t":"abc-1","d":"2017-12-29 12:42:53"}
{"t":"abc-2","d":"2017-12-29 12:43:05"}
{"t":"abc-3","d":"2017-12-30 14:42:09"}
{"t":"code-4","d":"2017-12-30 14:42:20"}
So each one is a separate json entity
$filename = "folder/filename.json";
$lines=file( $filename );
foreach( $lines as $line ){
$obj=json_decode( $line );
$t=$obj->t;
$d=$obj->d;
/* do something with constituent pieces */
echo $d,$t,'<br />';
}
并像这样使用
macro_rules! assign{
{($v1:ident, $v2:ident) = $e:expr} =>
{
let (v1, v2) = $e;
$v1 = v1;
$v2 = v2;
};
{($v1:ident, $v2:ident, $v3:ident) = $e:expr} =>
{
let (v1, v2, v3) = $e;
$v1 = v1;
$v2 = v2;
$v3 = v3;
}; // and so on
}