banner
lzyoo

lzyoo

本人职业:前端开发工程师 工作年限:三年 技术栈:React、Vue、Nest、Python 一直在努力,一直在放弃,好想有一个引路人带领。

Learning Rust (1) Data Types

String#

  • I found that Rust strings are very different from my JavaScript!! You can't learn all languages with the mindset of one language.
  • String is a wrapper around a Vec<u8>, not a real string!
  1. Creating a string
`String::new` is used to create an empty string instance, with no parameters
let mut s = String::new();

`String::from` is used to create a string instance, using &str type as a parameter
let mut ss = String::from("I am rust");
// Equivalent
let mut ss = "I am rust".to_string();

I see that the types returned by the editor are the same, so you can use whichever you want in daily use.
  1. Common string operations
// Return string length
ss.len(); // 10 
// Return whether the string is empty
ss.is_empty(); // false
// Convert string to byte values
ss.into_bytes(); // [230, 136, 145, 230, 152, 175, 114, 117, 115, 116, 229, 164, 169, 228, 184, 139, 230, 151, 160, 230, 149, 140]
// Lowercase
ss.to_lowercase(); // I am rust
// Uppercase
ss.to_uppercase(); // I AM RUST
// Return a string slice with leading and trailing whitespace removed
ss.trim(); // I am rust

// Parse string slice to other types
let num: u32 = "22".parse().unwrap();

// Append string, takes a &str type
ss.push_str("Unbeatable"); // I am rust Unbeatable

// The character occupies 3 bytes, so it will report an error; it works normally with letters
// If ss value is rust
ss.insert_str(1, "Unbeatable"); // rUnbeatableust

// Check if it contains the parameter value
ss.contains("r") // true
// Check if it starts with the parameter value
ss.starts_with("I") // true
// Check if it ends with the parameter value
ss.ends_with("t") // true
// Check the index of the byte
ss.find("r") // Some(6)
// String replacement
ss.replace("rust", "c++") // I am c++

Numbers#

Integer#

The difference between signed and unsigned is whether it can be negative

  • Values that can be negative use signed types
  • Values that are always positive use unsigned types
LengthSignedUnsigned
8i8u8
16i16u16
32i32u32
64i64u64
128i128u128
archisizeusize

Floating Point#

f32 and f64
Rust's default floating-point type is f64

Some simple operations and built-in methods#

let sum = 99 + 1; // 100

let difference = 100 - 1; // 99

let multip = 4 * 30; // 120

let div = 6 / 3; // 2

let truncated = -6 / 3; // -2

let remainder = 43 % 5; // 3

// Absolute value
(-10i32).abs(); // 10
// Absolute difference
(-10i32).abs_diff(5); // 15

Boolean#

No difference from other languages

Tuple#

Usage scenarios

  1. Function parameter passing
  2. Return value types
let tuple = (5, "Rust", true);
// Access
let number = tuple.0; // 5

let student_tuple = ("RR", 100);

fn tuple_match((name, score): (&str, u32)) -> String {
	match score {
		90..=100 => format!("Excellent performance in {} course, score is {}, excellent!",
		80..=89 => format!("Good performance in {} course, score is {}, good!", course_name, score),
		70..=79 => format!("Average performance in {} course, score is {}, pass!", course_name, score),
		_ => format!("Need to work hard in {} course, score is {}, fail.", course_name, score),
	}
}
tuple_match(student_tuple) // RR performed excellently in the course, score is 100, excellent!

Array#

Array#

  1. A collection of elements with a fixed length, and the types must be uniform.
  2. Does not support addition or deletion operations.
let mut numbers: [i32; 5] = [1, 2, 3, 4, 5];
// Access array elements
println!("First element: {}", numbers[0]);
println!("Last element: {}", numbers[4]);
// Modify elements in the array
numbers[2] = 20;
println!("Modified third element: {}", numbers[2]);
// Iterate over the array
for elem in numbers.iter() {
    println!("{}", elem);
}
// Create an array using array literal
let array_literal: [i32; 6] = [0; 6];
println!("Array initialized with literal: {:?}", array_literal);

Vec#

  1. A collection of elements with dynamic size
  2. Supports addition and deletion operations.
let mut vec: Vec<i32> = Vec::new();
vec.push(1);
vec.push(2);
vec.push(3);
// Equivalent
let mut vec = vec![1, 2, 3];
// Equivalent
let mut vec = Vec::from([1, 2, 3]);

vec.len(); // 2
// Pop the last element value
vec.pop(); // Some(2)
// Add new element
vec.push(99); // [1, 2, 3, 99]
// Remove value by index
vec.remove(0); // [2, 3]
// Match value
vec.contains(&3); // true
// Sort
vec!["hello", "world"].join(" "); // hello world
vec.sort(); // [1, 2, 3]
// Slice, returns an iterator over the slice elements
let mut chunks = vec.chunks(2);
chunks.next().unwrap(); // &[1, 2]
chunks.next().unwrap(); // &[3]

// Access
println!("First element: {}", vec[0]);
println!("Last element: {}", vec[2]);
// Iterate
for i in vec {
    println!("Array initialized with literal: {}", i);
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.