• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

4.3 rust func closure

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

fn  add_one_v1   (x: u32) -> u32 { x + 1 }
let add_one_v2 = |x: u32| -> u32 { x + 1 };
let add_one_v3 = |x|             { x + 1 };
let add_one_v4 = |x|               x + 1  ;

 

pub fn test3() {
    let example_closure = |x| x;

    let s = example_closure(String::from("hello"));
    let n = example_closure(5);
}

 

  --> src/base/k_closure.rs:53:29
   |
53 |     let n = example_closure(5);
   |                             ^
   |                             |
   |                             expected struct `String`, found integer
   |                             help: try using a conversion method: `5.to_string()`

The first time we call example_closure with the String value, the compiler infers the type of x and the return type of the closure to be String. Those types are then locked into the closure in example_closure, and we get a type error if we try to use a different type with the same closure.

 

不换数据类型,下面的是正确的

pub fn test3() {
    let example_closure = |x| x;

    let s = example_closure(6);
    println!("{}",s);
    let n = example_closure(5);
    println!("{}",n);
}

 

6
5

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
【转载】Matlab与C#连接的几种方式比较发布时间:2022-07-18
下一篇:
【V2.0更新】基于MATLAB的傅里叶级数可视化发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap