V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
rustacean
V2EX  ›  Rust

Rust 中 println! 是 expression 还是 statement ?

  •  
  •   rustacean · 2016-12-28 10:29:17 +08:00 via iPhone · 4104 次点击
    这是一个创建于 2648 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在看 *The Rust Programming Language* 的时候 Functions 这一节讲到 expression 和 statement 的区别。想弄明白 *println!* 是 expression 还是 statement . 找到这两篇答案:

    - 是 [statement]( https://users.rust-lang.org/t/expression-statements/7733)
    >since it has a semicolon, it's a statement. And if you have a block like { statement; statement; expression } then that final expression becomes the value for the whole block.

    - 是 [expression]( http://stackoverflow.com/a/28439789/4974466)
    >'println!()' is a macro expanding to an expression. It has no useful return value, but it is an expression (mostly because almost everything is an expression, including function calls and blocks).
    能有前辈解释一下正确的理解是什么嘛?
    6 条回复    2018-09-04 20:14:34 +08:00
    realwangyibo
        1
    realwangyibo  
       2016-12-28 12:26:13 +08:00
    println!("Naive")是表达式,宏展开是表达式,表达式的值是 ()

    表达式语句是在表达式后跟分号,将表达式变成语句, println!("Naive");是语句
    realwangyibo
        2
    realwangyibo  
       2016-12-28 12:42:37 +08:00
    鄙人认为,表达式是无法被执行的,只有语句可以。

    do_something_with_vector(&mut vector) 是函数调用表达式,只是相当于把干柴堆好。

    do_something_with_vector(&mut vector); 是函数调用(表达式)语句,在堆好干柴的情况下点一把火。

    ; 也是语句,只不过没有柴,点多少次火都没什么用。
    rustacean
        3
    rustacean  
    OP
       2016-12-28 12:46:10 +08:00 via iPhone
    @realwangyibo 谢谢您
    peng1999
        4
    peng1999  
       2016-12-29 19:19:46 +08:00 via Android
    @realwangyibo 我倒觉得表达式的求值过程才是算程序的执行,分号只是在多个表达式顺序求值是使用。例如,最后一个语句是可以不写分号的。
    realwangyibo
        5
    realwangyibo  
       2016-12-29 20:28:40 +08:00 via iPhone
    @peng1999 block 是表达式, block 的值取决于最后的表达式的值。如果最后的是语句,则 block 的值是(),所以最后不写分号的,是表达式而不是语句。

    求值的方式是表达式规定的,但「求值」这个动作是表达式语句执行的。
    sidgwick
        6
    sidgwick  
       2018-09-04 20:14:34 +08:00
    @realwangyibo 求值也是表达求值吧, 语句是没有值的. 还有 Rust 里面是不是没有表达式语句这种说法?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5323 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 08:25 · PVG 16:25 · LAX 01:25 · JFK 04:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.