[Rust] Implicitly returning values from functions

Code has error:

fn main() {
    let answer = square(3);
    println!("The square of 3 is {}", answer);
}

fn square(num: i32) -> i32 {
    num * num;
}

Error:

⚠️  Compiling of exercises/functions/functions5.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
  --> exercises/functions/functions5.rs:12:24
   |
12 | fn square(num: i32) -> i32 {
   |    ------              ^^^ expected `i32`, found `()`
   |    |
   |    implicitly returns `()` as its body has no tail or `return` expression
13 |     num * num;
   |              - help: remove this semicolon to return this value

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.

 

If we do:

fn square(num: i32) -> i32 {
    num * num
}

That will works, because without ;, Rust consider that line as implicity return value, if you have ;, you need to add returnkeyword:

fn square(num: i32) -> i32 {
    return num * num;
}

 

posted @   Zhentiw  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-02-23 [Typescript] NoInfer
2023-02-23 [Typescript] OVerride external library Types
2022-02-23 [Whole Web] SQL INJECTION
2022-02-23 [Whole Web] CROSS SITE SCRIPTING (XSS)
2019-02-23 [Functional Programming] Pointy Functor Factory
2019-02-23 [Functional Programming] Async IO Functor
2017-02-23 [HTML5] Focus management using CSS, HTML, and JavaScript
点击右上角即可分享
微信分享提示