通过Rust编译时出现的错误来学习Rust
通过Rust编译时出现的错误来学习Rust
cannot assign twice to immutable variable x
不能复制两次不可变x
fn main() {let x = 5; // solution: let mut x = 5;println!("The value of x is {}", x);x = 6;println!("The value of x is {}", x);
}
consider giving guess
a type
尝试给guess
类型
let guess = "32".trim().parse().expect("Not a number!");
/// solution: let guess:i32 = "32".trim().parse().expect("Not a number!");
index out of bounds: the length is 2 but the index is 2
越界
fn main() {let elements = [1, 2];let index = 2;println!("The value of elements is {}", elements[index]);// reviewlet value:i8;let value:i32;let value:i64;let value:isize;let value:u8;let value:u32;let value:u64;let value:usize;let value = 92_222;let value = 0xfff;let value = 0o77;let value = 0b1111_0000;let value = b'A';let value: f64 = 2.0;let value: f32 = 3.0;let value:bool = true;let value:char = 'Z';let value: (i32, bool) = (1, true);let value1 = value.0;let value2 = value.1;let (value, valueB) = value;let value:[i32; 3] = [1, 2, 3];let value = [3; 3]; // [3, 3, 3]let value1 = value[0];
}
expected expression, found statement (let
)
期望是表达式,但发现是语句
let valueA = (let valueB = 6);
mismatched types
类型不匹配
fn main() {let x = plus_value(5);println!("The value of x {}", x);
}fn plus_value(value: i32) -> i32 {value + 5;
}/// 错误如下fn plus_value(value: i32) -> i32 {---------- ^^^ expected `i32`, found `()` 期望是 i32, 但是发现是空元组|implicitly returns `()` as its body has no tail or `return` expressionvalue + 5;- help: consider removing this semicolon 帮助: 建议是移除分号
expected bool
, found integer
fn main() {let number = 3;if number { // solution: if number == 3 {println!("continue was true");}else {println!("continue was false");}
}
if
and else
have incompatible types
fn main() {let number = 3;if number == 3 {println!("continue was true");}else if number == 2 {println!("continue was false");}let value = if number == 3 {"The number is 3"}else {5 // solution: "5"};
}
Loop
fn main() {let mut couter = 0;let result = loop {couter += 1;if couter == 10 {break couter * 2;}};println!("result: {}", result);while couter > 0 {println!("couter: {}", couter);couter -= 1;}let elements = [1, 2];for element in elements.iter() {println!("element: {}", element);}for number in (0..4).rev() {println!("number: {}", number);}
}
borrow of moved value: xxx
// error
let string1 = String::from("Hello");------- move occurs because `string1` has type `String`, which does not implement the `Copy` trait发生移动,是因为类型String不具有Copy特性
let string2 = string1;------- value moved here
println!("string1 {}", string1);^^^^^^^ value borrowed here after movevalue移动后这里又再次使用
cannot borrow s
as mutable more than once at a time
fn main() {let mut s = String::from("Hello");push_str(&mut s);// println!("{}", s);let r1 = &mut s; /// 一次声明只能一次可变引用let r2 = &mut s;println!("r1 {}", r1);{let r1 = &mut s;println!("r1 {}", r1);}{let r2 = &mut s;println!("r2 {}", r2);}}fn push_str(s: &mut String) {s.push_str(" World!");
}
cannot borrow s
as mutable because it is also borrowed as immutable
fn main() {let mut s = String::from("Hello");let r1 = &s;let r2 = &s;let r3 = &mut s;println!("r1 {}", r1);
}
expected named lifetime parameter
fn main() {let Hello = dangle();
}// 悬垂引用
fn dangle() -> &String {let value = String::from("Hello");&value
}
cannot borrow s
as mutable because it is also borrowed as immutable
fn main() {let mut s = String::from("Hello World!");let world = first_word(&s);s.clear();println!("s {} world {}", s, world);
}fn first_word(s: &String) -> &str {let bytes = s.as_bytes();for (i, &item) in bytes.iter().enumerate() {if item == b' ' {return &s[0..i]}}return &s[..]
}
Struct
fn main() {let user1 = User {username: String::from("someone"),email: String::from("someone@qq.com"),};let user2 = User {username: user1.username,..user1};
}fn build_user(username: String, email: String,) -> User {return User {username, email,};
}struct User {username: String,email: String,
}
#[derive(Debug)]
struct Rectangle {width: u32,height: u32,
}impl Rectangle {fn area(&self) -> u32 {self.width * self.height}fn square(size: u32) -> Rectangle {Rectangle { width: size, height: size}}
}impl Rectangle {fn can_hold(&self, other: &Rectangle) -> bool {self.width == other.width && self.height == other.height}
}fn main() {let rect = Rectangle { width: 30, height: 30 };println!("rect {:?} area {:?}", rect, rect.area());
}
struct
enum IpAddrKind {V4,V6,
}struct IpAddr {kind: IpAddrKind,address: String,
}fn main() {let home = IpAddr {kind: IpAddrKind::V4,address: String::from("127.0.0.1"),};let loopback = IpAddr {kind: IpAddrKind::V6,address: String::from("::1"),};
}
Enum
enum IpAddr {V4(String),V6(String),
}let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));enum Message {Quit,Move { x: i32, y: i32 },Write(String),ChangeColor(i32, i32, i32),
}struct QuitMessage; // unit struct
struct MoveMessage {x: i32,y: i32,
}
struct WriteMessage(String); // tuple struct
struct ChangeColorMessage(i32, i32, i32); // tuple structimpl Message {fn call(&self) {// method body would be defined here}
}
let m = Message::Write(String::from("hello"));
m.call();
non-exhaustive patterns: &None
not covered
fn plus_one(x: &Option<i32>) -> Option<i32> {match x {Some(i) => Some(i + 1),}
}fn main() {let a: i32 = 1;let b: Option<i32> = Some(5);//let c = a + b; /// 错误//println!("{}", c);plus_one(&b);
}
If let
fn main() {let some_u8_value = Some(3);match some_u8_value {Some(3) => println!("Three"),_ => ()}if let Some(4) = some_u8_value {println!("Three!");}else {println!("No match!");}
}
通过Rust编译时出现的错误来学习Rust
cannot assign twice to immutable variable x
不能复制两次不可变x
fn main() {let x = 5; // solution: let mut x = 5;println!("The value of x is {}", x);x = 6;println!("The value of x is {}", x);
}
consider giving guess
a type
尝试给guess
类型
let guess = "32".trim().parse().expect("Not a number!");
/// solution: let guess:i32 = "32".trim().parse().expect("Not a number!");
index out of bounds: the length is 2 but the index is 2
越界
fn main() {let elements = [1, 2];let index = 2;println!("The value of elements is {}", elements[index]);// reviewlet value:i8;let value:i32;let value:i64;let value:isize;let value:u8;let value:u32;let value:u64;let value:usize;let value = 92_222;let value = 0xfff;let value = 0o77;let value = 0b1111_0000;let value = b'A';let value: f64 = 2.0;let value: f32 = 3.0;let value:bool = true;let value:char = 'Z';let value: (i32, bool) = (1, true);let value1 = value.0;let value2 = value.1;let (value, valueB) = value;let value:[i32; 3] = [1, 2, 3];let value = [3; 3]; // [3, 3, 3]let value1 = value[0];
}
expected expression, found statement (let
)
期望是表达式,但发现是语句
let valueA = (let valueB = 6);
mismatched types
类型不匹配
fn main() {let x = plus_value(5);println!("The value of x {}", x);
}fn plus_value(value: i32) -> i32 {value + 5;
}/// 错误如下fn plus_value(value: i32) -> i32 {---------- ^^^ expected `i32`, found `()` 期望是 i32, 但是发现是空元组|implicitly returns `()` as its body has no tail or `return` expressionvalue + 5;- help: consider removing this semicolon 帮助: 建议是移除分号
expected bool
, found integer
fn main() {let number = 3;if number { // solution: if number == 3 {println!("continue was true");}else {println!("continue was false");}
}
if
and else
have incompatible types
fn main() {let number = 3;if number == 3 {println!("continue was true");}else if number == 2 {println!("continue was false");}let value = if number == 3 {"The number is 3"}else {5 // solution: "5"};
}
Loop
fn main() {let mut couter = 0;let result = loop {couter += 1;if couter == 10 {break couter * 2;}};println!("result: {}", result);while couter > 0 {println!("couter: {}", couter);couter -= 1;}let elements = [1, 2];for element in elements.iter() {println!("element: {}", element);}for number in (0..4).rev() {println!("number: {}", number);}
}
borrow of moved value: xxx
// error
let string1 = String::from("Hello");------- move occurs because `string1` has type `String`, which does not implement the `Copy` trait发生移动,是因为类型String不具有Copy特性
let string2 = string1;------- value moved here
println!("string1 {}", string1);^^^^^^^ value borrowed here after movevalue移动后这里又再次使用
cannot borrow s
as mutable more than once at a time
fn main() {let mut s = String::from("Hello");push_str(&mut s);// println!("{}", s);let r1 = &mut s; /// 一次声明只能一次可变引用let r2 = &mut s;println!("r1 {}", r1);{let r1 = &mut s;println!("r1 {}", r1);}{let r2 = &mut s;println!("r2 {}", r2);}}fn push_str(s: &mut String) {s.push_str(" World!");
}
cannot borrow s
as mutable because it is also borrowed as immutable
fn main() {let mut s = String::from("Hello");let r1 = &s;let r2 = &s;let r3 = &mut s;println!("r1 {}", r1);
}
expected named lifetime parameter
fn main() {let Hello = dangle();
}// 悬垂引用
fn dangle() -> &String {let value = String::from("Hello");&value
}
cannot borrow s
as mutable because it is also borrowed as immutable
fn main() {let mut s = String::from("Hello World!");let world = first_word(&s);s.clear();println!("s {} world {}", s, world);
}fn first_word(s: &String) -> &str {let bytes = s.as_bytes();for (i, &item) in bytes.iter().enumerate() {if item == b' ' {return &s[0..i]}}return &s[..]
}
Struct
fn main() {let user1 = User {username: String::from("someone"),email: String::from("someone@qq.com"),};let user2 = User {username: user1.username,..user1};
}fn build_user(username: String, email: String,) -> User {return User {username, email,};
}struct User {username: String,email: String,
}
#[derive(Debug)]
struct Rectangle {width: u32,height: u32,
}impl Rectangle {fn area(&self) -> u32 {self.width * self.height}fn square(size: u32) -> Rectangle {Rectangle { width: size, height: size}}
}impl Rectangle {fn can_hold(&self, other: &Rectangle) -> bool {self.width == other.width && self.height == other.height}
}fn main() {let rect = Rectangle { width: 30, height: 30 };println!("rect {:?} area {:?}", rect, rect.area());
}
struct
enum IpAddrKind {V4,V6,
}struct IpAddr {kind: IpAddrKind,address: String,
}fn main() {let home = IpAddr {kind: IpAddrKind::V4,address: String::from("127.0.0.1"),};let loopback = IpAddr {kind: IpAddrKind::V6,address: String::from("::1"),};
}
Enum
enum IpAddr {V4(String),V6(String),
}let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));enum Message {Quit,Move { x: i32, y: i32 },Write(String),ChangeColor(i32, i32, i32),
}struct QuitMessage; // unit struct
struct MoveMessage {x: i32,y: i32,
}
struct WriteMessage(String); // tuple struct
struct ChangeColorMessage(i32, i32, i32); // tuple structimpl Message {fn call(&self) {// method body would be defined here}
}
let m = Message::Write(String::from("hello"));
m.call();
non-exhaustive patterns: &None
not covered
fn plus_one(x: &Option<i32>) -> Option<i32> {match x {Some(i) => Some(i + 1),}
}fn main() {let a: i32 = 1;let b: Option<i32> = Some(5);//let c = a + b; /// 错误//println!("{}", c);plus_one(&b);
}
If let
fn main() {let some_u8_value = Some(3);match some_u8_value {Some(3) => println!("Three"),_ => ()}if let Some(4) = some_u8_value {println!("Three!");}else {println!("No match!");}
}
Vec
fn main() {let mut v:Vec<i32> = Vec::new();let mut v = vec![1,2,3,4,5];v.push(5);let third: &i32 = &v[2];println!("The third element is {}", third);match v.get(2) {Some(third) => println!("The third element is {}", third),None => println!("There is no third element."),}//let does_not_exist = &v[100];let does_not_exist = v.get(100); // 不会报错正常返回Noneprintln!("does_not_exist: {:?}", does_not_exist);
}
cannot borrow v
as mutable because it is also borrowed as immutable
fn main() {let mut v = vec![1, 2, 3, 4, 5];let first = &v[0];v.push(6);println!("The first element is: {}", first); // solution:This line of code moves to the previous line
}
Vec
enum SpreadsheetCell {Int(i32),Float(f64),Text(String),
}fn main() {let mut v = vec![1, 2, 3, 4, 5];for i in &mut v {*i += 50;}println!("elements is {:?}", v);// 使用枚举存储多种类型let row = vec![SpreadsheetCell::Int(3),SpreadsheetCell::Text(String::from("blue")),SpreadsheetCell::Float(10.12),];
}
String
fn main() {let mut s = String::new();let data = "initial contents";let s = data.to_string();// the method also works on a literal directly:let s = "initial contents".to_string();let s1 = String::from("Hello, ");let s2 = String::from("world!");let s3 = s1 + &s2; /// 这里的s1借出去了,后s1无法使用println!("s3 {} s1 {}", s3, s1);
}
HashMap
use std::collections::HashMap;fn main() {let text = "hello world wonderful world";let mut map = HashMap::new();for word in text.split_whitespace() {let count = map.entry(word).or_insert(0);*count += 1;}println!("{:?}", map);
}
通过Rust编译时出现的错误来学习Rust相关推荐
- 编译时遇到如下错误error C2061: syntax error : identifier 'THIS_FILE'
上午写程序时,加入了前些写的一个类,编译时遇到如下错误: ...error C2061: syntax error : identifier 'THIS_FILE' .../new(35) : err ...
- 使用CMake编译时出现动态链接库错误no version information available的解决方案
出现问题 在使用cmake编译时出现如下错误: /usr/local/bin/cmake: /home/0123/anaconda2/lib/libssl.so.1.0.0: no version i ...
- c语言编译时检查逻辑错误吗,C语言陷阱与技巧20节,自定义“编译时”assert方法,在代码编译阶段检查“逻辑”错误...
在C语言程序开发中,程序员写代码时应该考虑的"面面俱到",这样才能写出功能稳定的程序.例如,在实现 open() 函数时,先完成它的功能固然是重要的,但是程序员还需要考虑各种&qu ...
- VS编译时一些常见错误积累LNK,比如LNK2019、LNK2001(实时更新)
1. lnk2019 LNK2019错误一般是 compile 能找到 header(.h)文件,但是在链接时找不到需要的 lib 库文件或者是 dll 文件. 一般认为在编译 OSG 简单示例的时候 ...
- android源码下载,编译及编译时遇到的错误整理
一.环境搭建 因为android的源码编译只支持linux和mac,所以无法在windows下编译.我的电脑也没有双系统,因此只有装一个虚拟机.我用的是VMware workstation 我放到了百 ...
- PHP加密时遇到try错误,深入学习PHP错误与异常处理
一.PHP异常处理机制 由于我的工作岗位性质,我绝大部分的开发工作涉及到的操作风险都非常高,而且很频繁地使用其他部门提供的接口.所以,对于程序中可能出现的异常和错误都要有相应的处理方法,否则遗漏的话会 ...
- JAVA编译时出现的错误提示
1.错误:非法字符 看到这个错误提示,我们首先要考虑是否使用了中文字符 2.错误:找不到符号 看到这个错误,我们要考虑单词有没有拼写错误. 3.编译不报错,但是运行时出现错误 这种属于业务逻辑错误.环 ...
- 问题-Delphi2007编译时提示内存错误“sxs.dll. No Debug Info.ACCESS 0xXXXXX
相关资料:http://bbs.csdn.net/topics/340132341 问题现象:在调试程序时,未进工程文件中的TApplication.Run;证明不是代码问题. 问题原因:可能是因为* ...
- ISE14.7 综合编译时碰到错误
Win7 64位环境下,ISE14.7 综合编译时碰到以下错误 ERROR: MapLib:979 - LUT2 symbol "FSYNCIN1" (output signal= ...
- Qt使用信号与槽时出现的错误“Incompatible sender/receiver arguments”
在学习使用qt的过程中,没有好好的去了解信号与槽的机制,导致出现了这么一段代码: connect(timer1, SIGNAL(timeout()), this, SLOT(exeMonitor(QS ...
最新文章
- ORA-03113: end-of-file on communication channel Process ID: 252 Session ID: 1 Serial number: 3
- html中验证密码中是包含字母,在JavaScript中确认密码验证
- 团队第二次冲刺第三天
- postfix + cyrus-sasl2 + courier-authlib + Courier-IMAP + postfixadmin
- ★LeetCode(448)——找到所有数组中消失的数字(JavaScript)
- 组建优秀的团队-实现目标的开始
- libvirt 安装篇
- rip和ospf vrrp vlan综合实验
- WordPress百度熊掌号页面改造(纯代码实现)
- 严重: Servlet.service() for servlet [taotao-manager] in context with path [] threw exception [Request
- linux 系统如何启动服务,如何查看和停止Linux启动的服务
- 最难忘的一节计算机课,我最难忘的一节课
- 使用Vitamio插件显示花屏
- js 关键技术集合
- 浩瀚科技PDA移动开单|盘点机 数据采集器 条码扫描开单微POS软件 现场打印开单...
- RT-thread应用讲解——norflash
- Pose Invariant Embedding for Deep Person Re-identification论文翻译
- 微信企业向个人账户提现
- RFM会员价值度模型
- 微软的技术,直接颠覆了我对听书这件事的看法
热门文章
- Leetcode题解记录-动态规划
- 解决vim不能打开文件的问题
- 《微服务架构设计模式》读书笔记 | 第4章 使用Saga管理事务
- 阿里内部鄙视链!!!
- 多功能智能水杯设计方案
- Java中生成唯一ID的方法
- uniapp使用this.$refs.content.addEventListener提示 addEventListener is not a function 错误
- Gb28181国标目录的一个注意点,虚拟组织用斜杠分割的情况
- RabbitMQ Deep Dive (by quqi99)
- 微软并行模式库(PPL)