RUST学习笔记1
来源:互联网 发布:mac缓存文件夹在哪里 编辑:程序博客网 时间:2024/06/05 22:54
一直对rust比较关注,出于个人兴趣,对这种编译期检查的,没有GC的语言很感兴趣。希望能坚持下去吧。目前已经大致看了一遍语法,感觉上和c++还是比较像的。不过对于c++新增的机制,对于rust而言是作为基础而存在的。比如copy, move赋值,引用和可变引用,基于引用计数的内存管理等。还有学c++的时候没想明白的trait,现在想想实际上就是java的interface。
还有一些新东西过去没有接触过,比如rust的错误处理。很多时候写java的时候没有做错误处理,结果出了错误才想到去修复。而rust强迫你必须处理错误。
这里记录一些感觉上比较难的地方。
一个是这个borrow。在C++里,调用不同的构造函数对应不同的传值方式,有拷贝构造和MOVE构造,对应rust里实现了copy traits的是拷贝传值, 没有实现的就是borrow了。rust对于一个实例,一次只允许存在一个可变的引用存在,可以考虑为对象的读写锁。而不可变引用可以有很多个。
// A function which takes a closure as an argument and calls it.
fn apply<F>(f: F) where
// The closure takes no input and returns nothing.
F: FnOnce() {
// ^ TODO: Try changing this to `Fn` or `FnMut`.
f(); //这里为啥不直接 fn apply(f: FnOnce), 因为这里的apply针对所有类型的函数指针,因此apply本质是一个泛型函数。
}
// A function which takes a closure and returns an `i32`.
fn apply_to_3<F>(f: F) -> i32 where
// The closure takes an `i32` and returns an `i32`.
F: Fn(i32) -> i32 {
f(3)
}
fn main() {
use std::mem;
let greeting = "hello"; //greeting 这里是 ‘static str;
// A non-copy type.
// `to_owned` creates owned data from borrowed one
let mut farewell = "goodbye".to_owned(); //to_owned 创建了一个&str的引用。
// Capture 2 variables: `greeting` by reference and
// `farewell` by value.
let diary = || { //closure的traits类型由系统推导得到。其中FnOnce大于FnMut大于Fn.
// `greeting` is by reference: requires `Fn`.
println!("I said {}.", greeting);
// Mutation forces `farewell` to be captured by
// mutable reference. Now requires `FnMut`.
farewell.push_str("!!!");
println!("Then I screamed {}.", farewell);
println!("Now I can sleep. zzzzz");
// Manually calling drop forces `farewell` to
// be captured by value. Now requires `FnOnce`.
mem::drop(farewell);
};
// Call the function which applies the closure.
apply(diary);
// `double` satisfies `apply_to_3`'s trait bound
let double = |x| 2 * x;
println!("3 doubled: {}", apply_to_3(double));
}
- RUST学习笔记1
- Rust语言学习笔记(1)
- Rust学习笔记
- [Rust]学习笔记-序
- Rust语言学习笔记(2)
- Rust语言学习笔记(3)
- rust 学习入门
- rust学习网站
- 通过例子学习Rust之 1 Hello World
- Rust基础笔记:闭包
- Rust中文翻译1
- Rust中文翻译1
- Rust 1.12.1 发布
- 通过例子学习Rust 前言
- Rust基础语法概念学习
- rust
- 《Rust 程序设计语言》第一、二章笔记 WIN7下安装Rust
- Rust日志学习(一)—— 初识Rust log
- Mysql索引命令
- Faulty Odometer HDU
- A
- ajax 设置Access-Control-Allow-Origin实现跨域访问
- 利用QQ群”群中群”营销操作CPS月入上万
- RUST学习笔记1
- SpringMVC 使用uploadify插件上传文件,post方法无法直接获取参数问题
- 面向对象JAVA基础笔记
- 页面中的点击下拉框中获取数据
- linux函数跳转/头文件跳转
- equals()方法总结
- 水题:51Nod1095-Anigram单词
- 前后端分离尝试
- switch 语句