【问题标题】:How/when to use expressions instead of returns in rust如何/何时使用表达式而不是 Rust 中的返回值
【发布时间】:2022-12-05 06:10:53
【问题描述】:

我正在用 rust 编写代码来学习它(今天也是从 rust 书开始的,因为这种语言对我来说变得越来越有趣),我对如何遵守 rust 风格有一些疑问。

刚刚在书中读到,在 Rust 中,在函数末尾使用表达式比使用 return 语句更为惯用,所以过去几天我一直在经历挑战并为此重构它们,但我有一些疑问。

首先是我将其从返回更改为表达式的提交:

  1. https://github.com/nerock/AdventOfCode2022/commit/db9649760b18b92bf56de6586791285522caf2b4
  2. https://github.com/nerock/AdventOfCode2022/commit/b98b68c0fa8c7df0dcdba14eb642400468781084

    如果你看一下day1.rs方法get_top_three,我在创建变量的地方修改了它,并将它分配到if, else if, else中,但我最初的想法是根本没有else并有类似的东西

    if current > first {
        (current, first, second);
    } else if current > second {
        top_three = (first, current, second);
    } else if current > third {
        top_three = (first, second, current);
    }
    
    (first, second, third)
    

    这在某种程度上是可能的,也许更好吗?我已经习惯于避免使用 else 表达式并只返回“默认”结果,但也许这不是生锈的方式。

    除此之外,我仍然不确定何时使用 match 代替 if,所以如果你们中的任何人看过我的代码并且对我的使用有一些 cmets(或者说实话),我们将不胜感激.

    谢谢!

【问题讨论】:

  • 如果你想要一个开放式的代码审查,有一个专门的网站:Code Review。这些问题在 Stack Overflow 上太不具体了。
  • 嗨,感谢您的回答,但我不同意,主要部分确实是一个关于如何使用表达式而不是返回的具体问题,但除此之外我只是提到如果有人对我的 Rust 代码有 cmets 会有帮助,但不是主要是求review
  • 然后你应该编辑你的帖子并将其缩小到你想问的具体问题。
  • 但为什么?我最后怎么说我会感谢代码中的任何彗星会以某种方式损害我的问题可读性。对不起,我真的不明白是什么让你烦恼
  • @ner0ck 因为每个帖子只问一个问题是 stackoverflow 的政策;)如果我们投票结束一个问题,“一次问多个问题”甚至是我们可以输入的官方原因之一。它与 stackoverflow 的目的有关 - 它意味着其他人可以搜索的大量问答。而且,如果您提出多个问题或要求进行个人代码审查,那对其他人来说没有多大用处。正如其他人提到的那样,codereview 就是这个页面。

标签: rust return match expression


【解决方案1】:

由于缺少很多上下文和猜测,我假设您的问题如下。

你有代码:

fn get_top_three(current: i32, first: i32, second: i32, third: i32) -> (i32, i32, i32) {
    if current > first {
        return (current, first, second);
    } else if current > second {
        return (first, current, second);
    } else if current > third {
        return (first, second, current);
    }

    (first, second, third)
}

你听说最好不要做return,所以你将其重构为:

fn get_top_three(current: i32, first: i32, second: i32, third: i32) -> (i32, i32, i32) {
    let top_three: (i32, i32, i32);

    if current > first {
        top_three = (current, first, second);
    } else if current > second {
        top_three = (first, current, second);
    } else if current > third {
        top_three = (first, second, current);
    } else {
        top_three = (first, second, third)
    }

    top_three
}

现在你的问题是,这样更好吗?如果是,为什么?你能做些什么不同的事情?


答案是:是也不是。你缺少的是一切可以用作返回表达式。包括,在这种情况下非常重要,if 语句。

所以你可以像这样重写整个函数:

fn get_top_three(current: i32, first: i32, second: i32, third: i32) -> (i32, i32, i32) {
    if current > first {
        (current, first, second)
    } else if current > second {
        (first, current, second)
    } else if current > third {
        (first, second, current)
    } else {
        (first, second, third)
    }
}

也许考虑到这一点,您现在意识到这些表达式的真正强大 :)

【讨论】:

    猜你喜欢
    • 2012-05-15
    • 2015-12-30
    • 2020-11-09
    • 2013-03-26
    • 2018-02-25
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多