RUST初级例子


一 Rust第一个程序
[root@kolla rust]# rustc hello.rs && ./hello
Hello, world!
[root@kolla rust]# cat hello.rs
fn main(){
    println!("Hello, world!")
}
[root@kolla rust]# rustc hello.rs && ./hello
Hello, world!
[root@kolla rust]#

二 Rust if语句
2.1 if.rs

fn main(){
        let a = 1;
        if a == 1
        {
                println!("a is equal to 1")
        }
}
[root@kolla rust]# rustc if.rs && ./if
a is equal to 1
[root@kolla rust]#

2.2 if-else.rs

[root@kolla rust]# cat if-else.rs
fn main(){
  let a = 3;
  let b = 4;
  if a>b
  {
    println!("a is greater than b");
  }
  else
  {
    println!("a is smaller than b ");
  }
}
[root@kolla rust]# rustc if-else.rs && ./if-else
a is smaller than b
[root@kolla rust]#

三 Rust if in a let语句
在let语句的右侧使用if表达式,并将if表达式的值赋给let语句。
Let variable_name= if condition{  
  //code blocks  
}else{  
  //code block  
}//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/rust/rust-if-in-a-let-statement.html


[root@kolla rust]# cat if_in_let.rs
fn main(){
  let a = if true
         {1}
         else
         {2}
         ;
  println!("value of a is : {}", a);
}

[root@kolla rust]# rustc if_in_let.rs && ./if_in_let
value of a is : 1

四 Rust loop循环
4.1 loop循环
fn main(){
     loop  
     {  
         println!("Hello Yiibai");  
    }
}

[root@kolla rust]# cat loop.rs
fn main()
{
 let mut i=1;
 loop
 {
       println!("Hello Yiibai");
       if i==7
       {
         break;
       }
     i+=1;
 }
}
[root@kolla rust]# rustc loop.rs && ./loop
Hello Yiibai
Hello Yiibai
Hello Yiibai
Hello Yiibai
Hello Yiibai
Hello Yiibai
Hello Yiibai
[root@kolla rust]#

五 Rust for循环
for循环是条件循环,即循环运行特定次数。 Rust语言中for循环的行为与其他语言略有不同。 执行for循环直到条件为假。//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/rust/rust-for-loop.html

or循环的语法 - 
for var in expression  
{  
    //block statements  
}
Rust
在上面的语法中,表达式可以转换为迭代器,迭代器遍历数据结构的元素。 在每次迭代中,都从迭代器中获取值。 当没有剩余值被提取时,循环结束。//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/rust/rust-for-loop.html

5.1 
[root@kolla rust]# cat for.rs
fn main()
{
  for i in 1..11
  {
    print!("{} ",i)
  }
}
[root@kolla rust]# rustc for.rs && ./for
1 2 3 4 5 6 7 8 9 10 
    
5.2 
fn main()  
{  
    let mut result;  
    for i in 1..11  
    {  
        result=2*i;  
        println!("2*{}={}",i,result);  
    }  
}

5.3 
[root@kolla rust]# cat for_2.rs
fn main(){
 let fruits=["mango","apple","banana","litchi","watermelon"];
 for a in fruits.iter()
 {
   print!("{} ",a);
 }
}

[root@kolla rust]# rustc for_2.rs && ./for_2
mango apple banana litchi watermelon 
     
六 while循环
 fn main()  
{  
  let mut i=1;  
  while i<=10  
    {  
       print!("{}", i);  
       print!(" ");  
       i=i+1;  
    }  
}

fn main()  
{  
  let array=[10,20,30,40,50,60];  
  let mut i=0;  
  while i<6  
  {  
    print!("{}",array[i]);  
    print!(" ");  
    i=i+1;  
  }  
}

七 Rust所有权
7.1 Rust所有权
当代码块拥有资源时,它被称为所有权。 代码块创建一个包含资源的对象。 当控件到达块的末尾时,对象将被销毁,资源将被释放。
所有权的重点:

“所有者”可以根据可变性改变变量的拥有值。所有权可以转移到另一个变量。所有权只是在Rust中移动语义。所有权模型也保证了并行的安全性。
所有权规则

在Rust中,每个值都有一个与之关联的变量,并称为其所有者。一次只能有一个所有者。当所有者超出范围时,与其关联的值将被销毁。//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/rust/rust-ownership.html

[root@kolla rust]# rustc owner.rs && ./owner
Yiibai
a
a
[root@kolla rust]# cat owner.rs
fn main()
{
  let s=String::from("Yiibai");
  take_ownership(s);
  let ch='a';
  moves_copy(ch);
  println!("{}",ch);
}
fn take_ownership(str:String)
{
 println!("{}",str);
}
fn moves_copy(c:char)
{
  println!("{}",c);
}
[root@kolla rust]#


7.2
[root@kolla rust]# cat owner.rs
fn main()
{
  let s=String::from("Yiibai");
  take_ownership(s);
  let ch='a';
  moves_copy(ch);
  println!("{}",ch);
}
fn take_ownership(str:String)
{
 println!("{}",str);
}
fn moves_copy(c:char)
{
  println!("{}",c);
}
[root@kolla rust]# vi owner1.rs
[root@kolla rust]# rustc owner1.rs && ./owner1
value of x is 100
[root@kolla rust]#


八 Rust错误处理

8.1基础知识
错误处理是Rust确定出错的可能性并确认在代码进行编译之前采取某些操作的机制。此机制使程序更加健壮,因为能够在部署生产代码之前发现并处理错误。Rust编程语言不包含异常。
Rust中有两种类型的错误:
不可恢复的错误。可恢复的错误
可恢复的错误: 可恢复的错误是报告给用户的错误,用户可以重试该操作。 完全停止该过 程的可恢复错误并不严重。
                它由Result <T,E>表示。 可恢复错误的示例是“找不到文件”。T&E是通用参数。
                T->这是一种值,在成功的情况下返回一个’OK’变量。
                E->这是一种错误类型,在具有Err变体的故障情况下返回。
不可恢复的错误:当Rust报告一个不可恢复的错误时,那就是!宏停止执行程序。例如:“除以零”是不可恢复错误的示例。
[root@kolla rust]# cat assert1.rs
fn main()
{
    let x : bool = false;
    assert!(x==true);
}
[root@kolla rust]# ./assert1
thread 'main' panicked at 'assertion failed: x == true', assert1.rs:4:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
[root@kolla rust]#

      1 enum Value
      2 {
      3   Val,
      4 }
      5
      6 fn get_number(_:Value)->i32
      7 {
      8    5
      9 }
     10 fn find_number(val:Value)-> &'static str
     11 {
     12   match get_number(val)
     13   {
     14     7 => "seven",
     15     8=> "eight",
     16     _=> unreachable!()
     17   }
     18 }
     19
     20 fn main()
     21 {
     22   println!("{}", find_number(Value::Val));
     23 }


[root@kolla rust]# ./unreachable
thread 'main' panicked at 'internal error: entered unreachable code', unreachable.rs:16:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
[root@kolla rust]#

8.2 Rust不可恢复的错误
fn main()  
{  
   let v = vec![20,30,40];  
   print!("element of a vector is :",v[5]);  
}

运行结果
  Compiling playground v0.0.1 (/playground)
error: argument never used
 --> src/main.rs:4:38
  |
4 |    print!("element of a vector is :",v[5]);  
  |           -------------------------- ^^^^ argument never used
  |           |
  |           formatting specifier missing

error: aborting due to previous error

error: could not compile `playground`.

To learn more, run the command again with --verbose.

8.3 Rust可恢复的错误
可恢复的错误是那些完全停止程序并不严重的错误。可以处理的错误称为可恢复错误。它由Result <T,E>表示。 结果<T,E>是枚举,由两个变体组成,即OK <T>和Err <E>,它描述了可能的错误。

OK <T>:’T’是一种值,它在成功情况下时返回OK变量,这是一个预期的结果。
Err <E>:’E’是一种错误,它在失败情况下时返回ERR变量,这是意想不到的结果。

Enum Result<T,E>  
{  
    OK<T>,  
    Err<E>,  
}
在上面的例子中,Result是枚举类型,OK <T>&Err <E>是枚举类型的变体,其中'T'和'E'是泛型类型参数。
'T'是一种值,它将在成功的情况下返回,而'E'是一种错误,它将在失败的情况下返回。
Result包含泛型类型参数,因此在成功和失败值可能不同的许多不同情况下使用标准库中定义的结果类型和函数。

8.3.1
use std::fs::File;  
 fn main()   
{  
     let f:u32 = File::open("vector.txt");  
}

运行结果
   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
 --> src/main.rs:4:18
  |
4 |      let f:u32 = File::open("vector.txt");  
  |            ---   ^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`, found enum `std::result::Result`
  |            |
  |            expected due to this
  |
  = note: expected type `u32`
             found enum `std::result::Result<std::fs::File, std::io::Error>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

8.3.2
use std::fs::File;  
fn main()  
{  
   let f = File::open("vector.txt");  
   match f   
   {  
       Ok(file) => file,  
       Err(error) => {  
       panic!("There was a problem opening the file: {:?}", error)  
     },  
   }; 
}

程序说明

在上面的示例中,可以直接访问枚举变体,而无需在OK和Err变体之前使用Result::。
如果结果正常,则返回文件并将其存储在'f'变量中。 在匹配之后,可以在文件中执行读取或写入操作。匹配对Err值起作用。 
如果Result返回Error值,那么panic!运行并停止程序的执行。

8.3.4出错时 Error:unwrap()

九 Rust泛型与性状
9.1 泛型
当要创建多种形式的功能时,即,函数的参数可以接受多种类型的数据。 这可以通过泛型来实现。 泛型也称为“参数多态”,其中多态是多重的,而变形是形式。//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/rust/rust-generic.html
有两种方法可以提供通用代码
.Option<T>
.Result<T,E>
 

1.Option<T>:Rust标准库提供Option,其中'T'是通用数据类型。 它提供了一种类型的泛型。
enum Option<T>  
{  
    Some(T),  
    None,  
}
在上面的例子中,enum是自定义类型,其中<T>是通用数据类型。 可以用任何数据类型替换T。下面来看看这几个示例//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/rust/rust-generic.html

let x : Option<i32> = Some(10);  // 'T' is of type i32.  
let x : Option<bool> = Some(true);  // 'T' is of type bool.  
let x : Option<f64> = Some(10.5); // 'T' is of type f64.  
let x : Option<char> = Some('b'); // 'T' is of type char.//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/rust/rust-generic.html


let x : Option<i32> = Some(10.8);
左侧的类型是i32,右侧的值是f64类型。 因此,错误发生“类型不匹配”。

2 Result <T,E>: Rust标准库提供了另一种数据类型Result <T,E>,它是两种类型的泛型,即T&E://原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/rust/rust-generic.html
enum Result<T,E>  
   {  
      OK(T),  
        Err(E),  
}
注意:不得不使用'T'和'E',可以使用任何大写字母。

3 泛型函数
泛型可以在函数中使用,将泛型放在函数的签名中,其中指定参数的数据类型和返回值。
当函数包含类型为T的单个参数时。
fn function_name<T>(x:T)
<T>:给定的函数是一种类型的泛型
(x:T):x是类型T
当函数包含多个相同类型的参数时。
fn function_name<T>(x:T, y:T)   
// body of the function.
Rust
当函数包含多个类型的参数时。
fn function_name<T,U>(x:T, y:U)  
// Body of the function.

完整代码


9.2 Rust Trait


9.3 Rust生命周期


Rust智能指针
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值