首页 > 其他分享 >[Rust] Borrow checker

[Rust] Borrow checker

时间:2023-05-29 14:58:13浏览次数:22  
标签:count Item add Borrow item checker fn println Rust

Three rules:

  1. There can only be one value owner
  2. There can be unlimited immutable borrows (reference) with no mutable references
  3. There can be only one mutable reference and no immuntable references

 

There is one rule for lifetimes

  1. A reference cannnot outlive its value

Example

#[derive(Debug)]
struct MyStruct {
  age: usize
}
fn main() {
   let mut items: Vec<&MyStruct> = vec![];
   {
       let item = MyStruct {age: 0};
       items.push(&item); // item does not live long enough borrowed ..
   }
    
   println!("{:?}", items); // borrow later used here
}

 

Stated differently

  • One var owns the data
  • One var can change the data
  • Many vars can look at the data
  • You cannot look and change the data simultaneously
  • You cannot refer to something that has been dropped (released in memory)

 

Example:

#[derive(Debug)]
struct Item {
    count: usize
}

fn add_one(mut item: Item) {
    item.count += 1;
}

fn main() {
    let item = Item {count: 1};
    println!("{:?}", item);
    add_one(item);
    println!("{:?}", item);
}

//  let item = Item {count: 1}; this line owns the item
//  add_one(items); move the ownership to add_one function
//  println!("{:?}", item); this line will cause error because item is moved to add_one function

 

Next step:

fn add_one(item: &Item) {
    item.count += 1;
}

// item.count += 1; not mutable

fn main() {
    let item = Item {count: 1};
    println!("{:?}", item);
    add_one(&item);
    println!("{:?}", item);
}

Now we pass the reference. But now get not mutable error

 

Next step:

fn add_one(item: &mut Item) {
    item.count += 1;
}

fn main() {
    let item = Item {count: 1};
    println!("{:?}", item);
    add_one(&item); // error, consider mutably borrowing here: `&mut item`
    println!("{:?}", item);
}

 

Next step:

fn add_one(item: &mut Item) {
    item.count += 1;
}

fn main() {
    let item = Item {count: 1};
    println!("{:?}", item);
    add_one(&mut item); // error: cannot borrow `item` as mutable, as it is not declared as mutable
    println!("{:?}", item);
}

 

Next step:

fn add_one(item: &mut Item) {
    item.count += 1;
}

fn main() {
    let mut item = Item {count: 1};
    println!("{:?}", item);
    add_one(&mut item); 
    println!("{:?}", item);
}

 

标签:count,Item,add,Borrow,item,checker,fn,println,Rust
From: https://www.cnblogs.com/Answer1215/p/17440384.html

相关文章

  • Rust Web 全栈开发之连接数据库
    RustWeb全栈开发之连接数据库需要使用的crate和数据库sqlx,v0.5.10PostgreSQL创建项目~/rustvia......
  • rust 初识基础: 变量、数据类型、函数、所有权、枚举
    了解到rust和WebAssembly的结合使用,可以构建前端应用,而且性能也比较好。初步学习使用rust是预编译静态类型语言。安装rust官网下载rust-CN,大致了解下为什么选择:高性能、可靠性、生产力。打开控制台啊,执行安装(mac系统,windwos或其他系统查看官网)&>curl--proto......
  • Rust Web 全栈开发之 Actix 尝鲜并构建REST API
    RustWeb全栈开发之Actix尝鲜并构建RESTAPI一、Actix尝鲜需要使用的crateactix-webv4.3.1actix-rtv2.8.0~via......
  • Rust学习笔记——基础篇3:数据类型
    数据类型整数类型位长度有符号无符号8-biti8u816-biti16u1632-biti32u3264-biti64u64128-biti128u128archisizeusize整数型的表述方式进制例十进制98_222十六进制0xff八进制0o77二进制0b1111_0000字节(只能......
  • Rust Web 全栈开发之自建TCP、HTTP Server
    RustWeb全栈开发之自建TCP、HTTPServer课程简介预备知识Rust编程语言入门https://www.bilibili.com/video/BV1hp4y1k7SV课程主要内容WebService服务器端WebApp客户端WebApp(WebAssembly)Web框架:Actix数据库:PostgreSQL数据库连接:SQLx全部使用纯Rust编写!一......
  • Rust Tips 比较数值
    RustTips比较数值内容比较与类型转换浮点类型比较可以用这些运算符比较数值><==!=>=<=无法比较不同类型的值fnmain(){leta:i32=10;letb:u16=100;ifa<b{//报错mismatchedtypesprintln!("Tenislessthanonehundred.");......
  • rust设置国内镜像
    字节跳动镜像字节镜像crates.io镜像~/.cargo/config:[source.crates-io]#Tousesparseindex,change'rsproxy'to'rsproxy-sparse'replace-with='rsproxy'[source.rsproxy]registry="https://rsproxy.cn/crates.io-index"[so......
  • 使用 Rust 开发一个微型游戏
    使用Rust构建微型游戏--用于理解游戏开发一、创建游戏Agenda建立项目实现Gameloop不同的游戏模式添加玩家添加障碍和计分汇总理解Gameloop为了让游戏流畅、顺滑的运行,需要使用GameloopGameloop:初始化窗口、图形和其它资源每当屏幕刷新(通常是每秒30......
  • Rust async 编程
    Rustasync编程AsynchronousProgramminginRust:https://rust-lang.github.io/async-book/中文书名《Rust异步编程指南》:https://github.com/rustlang-cn/async-bookRust语言圣经(RustCourse):https://course.rs/advance/async/getting-started.html一、GettingStarted1.......
  • RustDesk,可私有部署的远程控制软件
    一、服务端:运行压缩包里面的RustDeskServer.Setup.exe安装即可  二、客户端:输入ID服务器IP地址即可开始连接,完全免费使用,无任何限制 ......