vimer linux kernel 爱好者

rust之基础入门

2021-01-05

install

首先要根据官网的指令把rust安装到pc上,其包管理器是Cargo.

hello world

fn main() {
    println!("hello, world");
}

保存为文件为 hello.rs. 然后使用命令rustc hello.rs去编译生成hello的二进制文件。

注释

rust的注释有三种,其中”/**/”和”//”与c/c++的注释方式一致,第三种方式是

/// Doc which are parsed into html, begin
//! end

格式打印

上面的println!就是将文本打印到console上并换行。

   println!("{ } days", 31);
   println!("{0}, this is {1}, {1} this is {0}", "yubo", "hechun");

”{}”会自动替换任何参数。指示词可以使用0和1自动填入参数,这样的参数在这里叫做位置参数Positional arguments。

还可以有 Named arguments. 比如下面这种:

	// name arg:
	 println!("{sub} {verb} {obj}",
            obj="vimer",
            verb="hello",
            sub = "test");
   // {:b} print it with binary format
   println!("{} of {:b} know binary, the other half does not", 1, 2);

   // Right-align text with a special width
   println!("{number:>width$}", number=1, width=6);

output:

test hello vimer
1 of 10 know binary, the other half does not
     1
 // Right-align text with a special width
   println!("{number:>width$}", number=1, width=6);

   println!("{number:>0width$}", number=1, width=6);
/*
1 of 10 know binary, the other half does not
     1
000001
*/

以上的代码中,包含了格式(二进制b,对其, 填充)等格式说明。

如果位置参数确实怎么办? rust会直接给你报错。

 println!("my name is {0}, and your name is {1}, {1} this is {0}", "vimer");

error:

error: invalid reference to positional argument 1 (there is 1 argument)
 --> hello.rs:2:47
  |
2 |    println!("my name is {0}, and your name is {1}, {1} this is {0}", "vimer");
  |                                                ^^^  ^^^
  |
  = note: positional arguments are zero-based

error: aborting due to previous error

debug

”” to debug rust program

type

Rust的类型比较特殊,是需要值得注意点。

fn main() {
    // Variables can be type annotated.
    let logical: bool = true;

    let a_float: f64 = 1.0;  // Regular annotation
    let an_integer   = 5i32; // Suffix annotation

    // Or a default will be used.
    let default_float   = 3.0; // `f64`
    let default_integer = 7;   // `i32`

    // A type can also be inferred from context
    let mut inferred_type = 12; // Type i64 is inferred from another line
    inferred_type = 4294967296i64;

    // A mutable variable's value can be changed.
    let mut mutable = 12; // Mutable `i32`
    mutable = 21;

    // Error! The type of a variable can't be changed.
    mutable = true;

    // Variables can be overwritten with shadowing.
    let mutable = true;
}

下面的代码把rust基本的数据总结下来了:

fn main() {
   println!("1+2={}", 1u32+2); // 3
   println!("1-2={}", 1i32-2); // -1
   println!("true and false is {}", true && false);// true and false is false
   println!("true or false is {}", true || false); // true or false is true
   println!("Not true is {}", !true); // Not true is false
    // bitwise
    println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101u32); //0011 AND 0101 is 0001
    println!("0011 or 0101 is {:04b}", 0b0011u32 | 0b0101u32);//0011 or 0101 is 0111
    println!("0011 XOR 0101 is {:04b}", 0b0011u32 ^ 0b0101u32); //0011 XOR 0101 is 0110
    println!("1 << 5 is {}", 1u32 << 5); // 1 << 5 is 32
    println!("0x80 >> 2 is {:x}", 0x80u32 >> 2); //
    println!("One million is written as {}", 1_000_000u32);// One million is written as 1000000
}

types

该修饰符可以改变变量的属性,主要是否可以改变其值的属性。

// first
	 let long_tuple = (1u8, 2u16, 3u32, 4u64,
                      -1i8, -2i16, -3i32, -4i64,
                      0.1f32, 0.2f64,
                      'a', true);
    // print content of tuple of indexing
    println!("first value {}", long_tuple.0);
    println!("second value {}", long_tuple.1);

    let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);
    // print tuples, 元组中有元组可以打印,
    println!("tuple of tuples: {:?}", tuple_of_tuples);
    let too_long_tuple = (1,2,3,4,5,6,7,8,9,10);
    println!("long tuple :{:?}", too_long_tuple); // 之前版本是不可以的,但是目前是可以的了

    // make pair for tuple
    let pair = (1, true);
    println!("pair is {:?}",pair);

    // 如果需要只打印一个元素的tuple,则需要","进行分割
    println!("the one element tupleis {:?}", (8i8,)); //p: the one element tupleis (8,)
    // 如果只有一个元素,就是单单打印一个元素
    println!("the one element {:?}", (8i8)); //p: the one element 8

// second

	let age = 28; // can not reassign value

	let mut age = 28;
	age = 36; // is ok

	const ID: i32 = 001; // ok

	// Assign multiple vars
	let (my_name , my_age ) = ("Brad", 37);
	println!("{} is {}, my_name, my_age");

	println!("Max i32 is {} and i64 is {}", std::i32::MAX, std::i64::MAX);


scope

rust是一个基于 block 的语言。

string

rust提供两种string的声明。一种是char*的形式,另一种是直接使用内置方法, 基于heap的内存模型。

	// 1
    let hello = "Hello"; // It is fixed-len string in memory

	// 2
	let hello = String::from("hello");
	println!("Length: {}",hello.len());

下面是个有趣的例子:

fn main() {
    let hello = String::from("hello ");
    hello.push("world");

    println!("{}", hello);
} // error! 1. let is default behave for immutable
// 2. push() is only for a word
//3. push_str() is supported for string

// right code :

fn main() {
    let mut hello = String::from("hello ");
    hello.push_str("world");
    hello.push('!');

    println!("{}", hello);
}

String的属性有

  1. capacity()
  2. is_empty()
  3. contains()
  4. Replace
  5. split_whitespace
for word in hello.split_whitespace(){
        println!("{}", word);
}
// hello
// world!
  1. Create string with capacity
	let mut s = String::with_capacity(10);
	s.push('a');
	s.push('b');

	assert_eq!(3, s.len); // debug track

tuple

Tuple group together value of different types, max is 12

	let person: (&str, &str, i8) = ("yubo", "vimer", 28);
    println!("{} is form {} and is {}", person.0, person.1, person.2);

array

It is the same elements in a array.

let num: [i32;5] = [1,2,3,4,5]; // [ypye; num]
    println!("{:?}", num);
// 1. 少一个元素都不行的

// 2. get a single val
	println!("{}", num[3]);

// 3. reassign value

// 4. Arrays are stack
	 println!("Array occupies {} bytes", std::mem::size_of_val(&num));
/* Array occupies 20 bytes
*/

std还可以使用 use std; 在rs源文件开始的地方。

Slices

Slices这里可以看成切片,同python的用法差不多。可以由 array 转化而来。

	let slice: &[i32] = &num;
	println!("Slices is {:?}", slice);
// Slices is [1, 2, 3, 4, 5]

如果在使用切片时指定下标,则使用符号..

 let slice: &[i32] = &num[0..2];
    println!("Slices is {:?}", slice);
// Slices is [1, 2]

vector

Vector is resize array, 目前看与array没有太大的区别。

fn main() {
    let mut num: Vec<i32> = vec![1,2,3,4,5];
    println!("{:?}", num);
    println!("{}", num[3]);
    // reassign value
    num[3] = 20;
    println!("Array occupies {} bytes", std::mem::size_of_val(&num));
    let slice: &[i32] = &num[0..2];
    println!("Slices is {:?}", slice);
}

则输出为:

[1, 2, 3, 4, 5]
4
Array occupies 24 bytes
Slices is [1, 2]

当然可以使用 push(), pop(),loop through vector values

for x in num.iter() {
	println!("number: {}", x);
} // this is immut_value

for x in num.iter_mut() {
	*x +x = 2;
}

conditions

if/else

 let age = 22;
    let check_id: bool = false;
    if age >= 21  && check_id{
        println!("haha");
    } else {
        println!("no you are not");
    }
// short of if
	let is_of_age = if age >= 21 { true } else { false };

loops

loop

 let mut count = 0;
    // infinite

    loop {
        count += 1;
        println!("Number: {}", count);
        if count == 20 {
            break;
        }
    }
/*
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10
Number: 11
Number: 12
Number: 13
Number: 14
Number: 15
Number: 16
Number: 17
Number: 18
Number: 19
Number: 20
   */

while

 while count <= 50 {
        if count % 15 == 0 {
            println!("fizzbuzz");
        } else if count % 3 == 0 {
            println!("fizee");
        } else if count % 5 == 0{
            println!("buzz");
        } else {
            println!("no {}", count);
        }
        count += 1;
    }

For loop

The same result as above code:

 for count in 0..50 {
        if count % 15 == 0 {
            println!("fizzbuzz");
        } else if count % 3 == 0 {
            println!("fizee");
        } else if count % 5 == 0{
            println!("buzz");
        } else {
            println!("no {}", count);
        }
    }

下一篇 rust-cargo-fun-

Comments

Content