当前位置: 首页 > news >正文

RustDay06------Exercise[81-90]

81.宏函数里面的不同的匹配规则需要使用分号隔开

// macros4.rs
//
// Execute `rustlings hint macros4` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONE#[rustfmt::skip]
macro_rules! my_macro {() => {println!("Check out my macro!");};($val:expr) => {println!("Look at this other macro: {}", $val);};
}fn main() {my_macro!();my_macro!(7777);
}

82.使用内部封装好的宏来替代某些常数

// clippy1.rs
//
// The Clippy tool is a collection of lints to analyze your code so you can
// catch common mistakes and improve your Rust code.
//
// For these exercises the code will fail to compile when there are clippy
// warnings check clippy's suggestions from the output to solve the exercise.
//
// Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONEuse std::f32;fn main() {let pi = f32::consts::PI;// 3.14f32;let radius = 5.00f32;let area = pi * f32::powi(radius, 2);println!("The area of a circle with radius {:.2} is {:.5}!",radius, area)
}

83.if let回顾

// clippy2.rs
// 
// Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a
// hint.// I AM  DONEfn main() {let mut res = 42;let option = Some(12);if let Some(x)=option {res += x;}println!("{}", res);
}

84.按照提示修改

这题说明 resize是原地操作 没有返回值

交换值必须要借助中间变量

// clippy3.rs
// 
// Here's a couple more easy Clippy fixes, so you can see its utility.
//
// Execute `rustlings hint clippy3` or use the `hint` watch subcommand for a hint.// I AM NOT DONE#[allow(unused_variables, unused_assignments)]
fn main() {let my_option: Option<()> = None;// if my_option.is_none() {//     my_option.unwrap();// }let my_arr = &[-1, -2, -3,-4, -5, -6,];println!("My array! Here it is: {:?}", my_arr);let my_empty_vec = vec![1, 2, 3, 4, 5];println!("This Vec is empty, see? {:?}", my_empty_vec);let mut value_a = 45;let mut value_b = 66;// Let's swap these two!let mut temp =0;temp=value_a;value_a = value_b;value_b = temp;println!("value a: {}; value b: {}", value_a, value_b);
}

85.使用as强制转换类型

// using_as.rs
//
// Type casting in Rust is done via the usage of the `as` operator. Please note
// that the `as` operator is not only used when type casting. It also helps with
// renaming imports.
//
// The goal is to make sure that the division does not fail to compile and
// returns the proper type.
//
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONEfn average(values: &[f64]) -> f64 {let total = values.iter().sum::<f64>();total / values.len() as f64
}fn main() {let values = [3.5, 0.3, 13.0, 11.7];println!("{}", average(&values));
}#[cfg(test)]
mod tests {use super::*;#[test]fn returns_proper_type_and_value() {assert_eq!(average(&[3.5, 0.3, 13.0, 11.7]), 7.125);}
}

86.大佬的奇特匹配orz

这题看了大佬的写法,太beautiful了(只有9行)

// from_into.rs
//
// The From trait is used for value-to-value conversions. If From is implemented
// correctly for a type, the Into trait should work conversely. You can read
// more about it at https://doc.rust-lang.org/std/convert/trait.From.html
//
// Execute `rustlings hint from_into` or use the `hint` watch subcommand for a
// hint.#[derive(Debug)]
struct Person {name: String,age: usize,
}// We implement the Default trait to use it as a fallback
// when the provided string is not convertible into a Person object
impl Default for Person {fn default() -> Person {Person {name: String::from("John"),age: 30,}}
}// Your task is to complete this implementation in order for the line `let p =
// Person::from("Mark,20")` to compile Please note that you'll need to parse the
// age component into a `usize` with something like `"4".parse::<usize>()`. The
// outcome of this needs to be handled appropriately.
//
// Steps:
// 1. If the length of the provided string is 0, then return the default of
//    Person.
// 2. Split the given string on the commas present in it.
// 3. Extract the first element from the split operation and use it as the name.
// 4. If the name is empty, then return the default of Person.
// 5. Extract the other element from the split operation and parse it into a
//    `usize` as the age.
// If while parsing the age, something goes wrong, then return the default of
// Person Otherwise, then return an instantiated Person object with the results// I AM NOT DONEimpl From<&str> for Person {fn from(s: &str) -> Person {let mut iter=s.trim().split(',');let name=iter.next().unwrap_or_default();let age = iter.next().and_then(|x| x.parse::<usize>().ok()).unwrap_or_default();match (name,age,iter.next().is_some()) {("",_,_) =>Person::default(),(_,0,_) => Person::default(),(_,_,true) =>Person::default(),(name,age,_) =>Person{name:name.to_string(),age},}}
}fn main() {// Use the `from` functionlet p1 = Person::from("Mark,20");// Since From is implemented for Person, we should be able to use Intolet p2: Person = "Gerald,70".into();println!("{:?}", p1);println!("{:?}", p2);
}#[cfg(test)]
mod tests {use super::*;#[test]fn test_default() {// Test that the default person is 30 year old Johnlet dp = Person::default();assert_eq!(dp.name, "John");assert_eq!(dp.age, 30);}#[test]fn test_bad_convert() {// Test that John is returned when bad string is providedlet p = Person::from("");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_good_convert() {// Test that "Mark,20" workslet p = Person::from("Mark,20");assert_eq!(p.name, "Mark");assert_eq!(p.age, 20);}#[test]fn test_bad_age() {// Test that "Mark,twenty" will return the default person due to an// error in parsing agelet p = Person::from("Mark,twenty");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_missing_comma_and_age() {let p: Person = Person::from("Mark");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_missing_age() {let p: Person = Person::from("Mark,");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_missing_name() {let p: Person = Person::from(",1");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_missing_name_and_age() {let p: Person = Person::from(",");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_missing_name_and_invalid_age() {let p: Person = Person::from(",one");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_trailing_comma() {let p: Person = Person::from("Mike,32,");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_trailing_comma_and_some_string() {let p: Person = Person::from("Mike,32,man");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}
}

下面是我自己的丑陋的写法

// from_into.rs
//
// The From trait is used for value-to-value conversions. If From is implemented
// correctly for a type, the Into trait should work conversely. You can read
// more about it at https://doc.rust-lang.org/std/convert/trait.From.html
//
// Execute `rustlings hint from_into` or use the `hint` watch subcommand for a
// hint.#[derive(Debug)]
struct Person {name: String,age: usize,
}// We implement the Default trait to use it as a fallback
// when the provided string is not convertible into a Person object
impl Default for Person {fn default() -> Person {Person {name: String::from("John"),age: 30,}}
}// Your task is to complete this implementation in order for the line `let p =
// Person::from("Mark,20")` to compile Please note that you'll need to parse the
// age component into a `usize` with something like `"4".parse::<usize>()`. The
// outcome of this needs to be handled appropriately.
//
// Steps:
// 1. If the length of the provided string is 0, then return the default of
//    Person.
// 2. Split the given string on the commas present in it.
// 3. Extract the first element from the split operation and use it as the name.
// 4. If the name is empty, then return the default of Person.
// 5. Extract the other element from the split operation and parse it into a
//    `usize` as the age.
// If while parsing the age, something goes wrong, then return the default of
// Person Otherwise, then return an instantiated Person object with the resultsimpl From<&str> for Person {fn from(s: &str) -> Person {let dataList:Vec<&str> =s.split(',').collect();println!("{:?}",dataList);// 数据量不对if dataList.len() != 2 || dataList[0]=="" || dataList[1]=="" {Person {name: String::from("John"),age: 30,}}else {if  dataList[1].chars().all(|x| x.is_digit(10)) {let uAge:usize = dataList[1].parse().unwrap();Person {name: dataList[0].to_string(),age: uAge,}}//    数据格式不对else {Person {name: String::from("John"),age: 30,}}}}
}fn main() {// Use the `from` functionlet p1 = Person::from("Mark,20");// Since From is implemented for Person, we should be able to use Intolet p2: Person = "Gerald,70".into();println!("{:?}", p1);println!("{:?}", p2);
}#[cfg(test)]
mod tests {use super::*;#[test]fn test_default() {// Test that the default person is 30 year old Johnlet dp = Person::default();assert_eq!(dp.name, "John");assert_eq!(dp.age, 30);}#[test]fn test_bad_convert() {// Test that John is returned when bad string is providedlet p = Person::from("");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_good_convert() {// Test that "Mark,20" workslet p = Person::from("Mark,20");assert_eq!(p.name, "Mark");assert_eq!(p.age, 20);}#[test]fn test_bad_age() {// Test that "Mark,twenty" will return the default person due to an// error in parsing agelet p = Person::from("Mark,twenty");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_missing_comma_and_age() {let p: Person = Person::from("Mark");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_missing_age() {let p: Person = Person::from("Mark,");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_missing_name() {let p: Person = Person::from(",1");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_missing_name_and_age() {let p: Person = Person::from(",");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_missing_name_and_invalid_age() {let p: Person = Person::from(",one");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_trailing_comma() {let p: Person = Person::from("Mike,32,");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}#[test]fn test_trailing_comma_and_some_string() {let p: Person = Person::from("Mike,32,man");assert_eq!(p.name, "John");assert_eq!(p.age, 30);}
}

87.对字符串进行合法判断

用我丑陋的写法写模拟orz,这题看看题目意思,知道大概要对字符串处理

正常返回Ok

错误返回错误类型

主要是凭感觉写的,这里面应该是通过系统库FromStr在创建的时候自动调用from_str来进行初始化,返回一个Person对象

// from_str.rs
//
// This is similar to from_into.rs, but this time we'll implement `FromStr` and
// return errors instead of falling back to a default value. Additionally, upon
// implementing FromStr, you can use the `parse` method on strings to generate
// an object of the implementor type. You can read more about it at
// https://doc.rust-lang.org/std/str/trait.FromStr.html
//
// Execute `rustlings hint from_str` or use the `hint` watch subcommand for a
// hint.use std::num::ParseIntError;
use std::str::FromStr;#[derive(Debug, PartialEq)]
struct Person {name: String,age: usize,
}// We will use this error type for the `FromStr` implementation.
#[derive(Debug, PartialEq)]
enum ParsePersonError {// Empty input stringEmpty,// Incorrect number of fieldsBadLen,// Empty name fieldNoName,// Wrapped error from parse::<usize>()ParseInt(ParseIntError),
}// I AM  DONE// Steps:
// 1. If the length of the provided string is 0, an error should be returned
// 2. Split the given string on the commas present in it
// 3. Only 2 elements should be returned from the split, otherwise return an
//    error
// 4. Extract the first element from the split operation and use it as the name
// 5. Extract the other element from the split operation and parse it into a
//    `usize` as the age with something like `"4".parse::<usize>()`
// 6. If while extracting the name and the age something goes wrong, an error
//    should be returned
// If everything goes well, then return a Result of a Person object
//
// As an aside: `Box<dyn Error>` implements `From<&'_ str>`. This means that if
// you want to return a string error message, you can do so via just using
// return `Err("my error message".into())`.impl FromStr for Person {type Err = ParsePersonError;fn from_str(s: &str) -> Result<Person, Self::Err> {if s.len() ==0  {return Err(ParsePersonError::Empty)}let vecData: Vec<&str> = s.split(',').collect();if vecData.len() !=2 {return Err(ParsePersonError::BadLen)}let name=String::from(vecData[0]);if name.is_empty() {return Err(ParsePersonError::NoName)}// 如果姓名字符串能转成usize   就赋值给agelet age = match vecData[1].parse::<usize>() {Ok(age)=>age,Err(e) => return Err(ParsePersonError::ParseInt(e))};Ok(Person {name,age})}
}fn main() {let p = "Mark,20".parse::<Person>().unwrap();println!("{:?}", p);
}#[cfg(test)]
mod tests {use super::*;#[test]fn empty_input() {assert_eq!("".parse::<Person>(), Err(ParsePersonError::Empty));}#[test]fn good_input() {let p = "John,32".parse::<Person>();assert!(p.is_ok());let p = p.unwrap();assert_eq!(p.name, "John");assert_eq!(p.age, 32);}#[test]fn missing_age() {assert!(matches!("John,".parse::<Person>(),Err(ParsePersonError::ParseInt(_))));}#[test]fn invalid_age() {assert!(matches!("John,twenty".parse::<Person>(),Err(ParsePersonError::ParseInt(_))));}#[test]fn missing_comma_and_age() {assert_eq!("John".parse::<Person>(), Err(ParsePersonError::BadLen));}#[test]fn missing_name() {assert_eq!(",1".parse::<Person>(), Err(ParsePersonError::NoName));}#[test]fn missing_name_and_age() {assert!(matches!(",".parse::<Person>(),Err(ParsePersonError::NoName | ParsePersonError::ParseInt(_))));}#[test]fn missing_name_and_invalid_age() {assert!(matches!(",one".parse::<Person>(),Err(ParsePersonError::NoName | ParsePersonError::ParseInt(_))));}#[test]fn trailing_comma() {assert_eq!("John,32,".parse::<Person>(), Err(ParsePersonError::BadLen));}#[test]fn trailing_comma_and_some_string() {assert_eq!("John,32,man".parse::<Person>(),Err(ParsePersonError::BadLen));}
}

88.判断rgb的合法范围

话说没看出来try的用处在哪里

// try_from_into.rs
//
// TryFrom is a simple and safe type conversion that may fail in a controlled
// way under some circumstances. Basically, this is the same as From. The main
// difference is that this should return a Result type instead of the target
// type itself. You can read more about it at
// https://doc.rust-lang.org/std/convert/trait.TryFrom.html
//
// Execute `rustlings hint try_from_into` or use the `hint` watch subcommand for
// a hint.use std::convert::{TryFrom, TryInto};#[derive(Debug, PartialEq)]
struct Color {red: u8,green: u8,blue: u8,
}// We will use this error type for these `TryFrom` conversions.
#[derive(Debug, PartialEq)]
enum IntoColorError {// Incorrect length of sliceBadLen,// Integer conversion errorIntConversion,
}// I AM NOT DONE// Your task is to complete this implementation and return an Ok result of inner
// type Color. You need to create an implementation for a tuple of three
// integers, an array of three integers, and a slice of integers.
//
// Note that the implementation for tuple and array will be checked at compile
// time, but the slice implementation needs to check the slice length! Also note
// that correct RGB color values must be integers in the 0..=255 range.// Tuple implementation
impl TryFrom<(i16, i16, i16)> for Color {type Error = IntoColorError;fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {if tuple.0>255 || tuple.0<0 ||tuple.1>255 || tuple.1<0 ||tuple.2>255 || tuple.2<0 {return Err(IntoColorError::IntConversion)}Ok(Color {red: tuple.0 as u8,green: tuple.1 as u8,blue: tuple.2 as u8,})}
}// Array implementation
impl TryFrom<[i16; 3]> for Color {type Error = IntoColorError;fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {if arr[0]<0 || arr[0]>255 || arr[1]<0 ||arr[1]>255 || arr[2]<0 ||arr[2]>255  {return Err(IntoColorError::IntConversion)}Ok(Color {red: arr[0] as u8,green: arr[1] as u8,blue: arr[2] as u8,})}
}// Slice implementation
impl TryFrom<&[i16]> for Color {type Error = IntoColorError;fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {if slice.len()!=3 {return Err(IntoColorError::BadLen)}if slice[0]<0 || slice[0]>255 ||slice[1]<0 || slice[1]>255 ||slice[2]<0 || slice[2]>255 {return Err(IntoColorError::IntConversion)}Ok(Color {red: slice[0] as u8,green: slice[1] as u8,blue: slice[2] as u8,})}
}fn main() {// Use the `try_from` functionlet c1 = Color::try_from((183, 65, 14));println!("{:?}", c1);// Since TryFrom is implemented for Color, we should be able to use TryIntolet c2: Result<Color, _> = [183, 65, 14].try_into();println!("{:?}", c2);let v = vec![183, 65, 14];// With slice we should use `try_from` functionlet c3 = Color::try_from(&v[..]);println!("{:?}", c3);// or take slice within round brackets and use TryIntolet c4: Result<Color, _> = (&v[..]).try_into();println!("{:?}", c4);
}#[cfg(test)]
mod tests {use super::*;#[test]fn test_tuple_out_of_range_positive() {assert_eq!(Color::try_from((256, 1000, 10000)),Err(IntoColorError::IntConversion));}#[test]fn test_tuple_out_of_range_negative() {assert_eq!(Color::try_from((-1, -10, -256)),Err(IntoColorError::IntConversion));}#[test]fn test_tuple_sum() {assert_eq!(Color::try_from((-1, 255, 255)),Err(IntoColorError::IntConversion));}#[test]fn test_tuple_correct() {let c: Result<Color, _> = (183, 65, 14).try_into();assert!(c.is_ok());assert_eq!(c.unwrap(),Color {red: 183,green: 65,blue: 14});}#[test]fn test_array_out_of_range_positive() {let c: Result<Color, _> = [1000, 10000, 256].try_into();assert_eq!(c, Err(IntoColorError::IntConversion));}#[test]fn test_array_out_of_range_negative() {let c: Result<Color, _> = [-10, -256, -1].try_into();assert_eq!(c, Err(IntoColorError::IntConversion));}#[test]fn test_array_sum() {let c: Result<Color, _> = [-1, 255, 255].try_into();assert_eq!(c, Err(IntoColorError::IntConversion));}#[test]fn test_array_correct() {let c: Result<Color, _> = [183, 65, 14].try_into();assert!(c.is_ok());assert_eq!(c.unwrap(),Color {red: 183,green: 65,blue: 14});}#[test]fn test_slice_out_of_range_positive() {let arr = [10000, 256, 1000];assert_eq!(Color::try_from(&arr[..]),Err(IntoColorError::IntConversion));}#[test]fn test_slice_out_of_range_negative() {let arr = [-256, -1, -10];assert_eq!(Color::try_from(&arr[..]),Err(IntoColorError::IntConversion));}#[test]fn test_slice_sum() {let arr = [-1, 255, 255];assert_eq!(Color::try_from(&arr[..]),Err(IntoColorError::IntConversion));}#[test]fn test_slice_correct() {let v = vec![183, 65, 14];let c: Result<Color, _> = Color::try_from(&v[..]);assert!(c.is_ok());assert_eq!(c.unwrap(),Color {red: 183,green: 65,blue: 14});}#[test]fn test_slice_excess_length() {let v = vec![0, 0, 0, 0];assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen));}#[test]fn test_slice_insufficient_length() {let v = vec![0, 0];assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen));}
}

89.as_ref与as_mut

as_ref用于将值转为引用

as_mut用于将值转为可变引用

在pow操作的时候需要一个拥有所有权的对象,所以需要调用as_mut方法

差不多是这个意思

// as_ref_mut.rs
//
// AsRef and AsMut allow for cheap reference-to-reference conversions. Read more
// about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html and
// https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively.
//
// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONE// Obtain the number of bytes (not characters) in the given argument.
// TODO: Add the AsRef trait appropriately as a trait bound.
fn byte_counter<T:AsRef<str>>(arg: T) -> usize {arg.as_ref().as_bytes().len()
}// Obtain the number of characters (not bytes) in the given argument.
// TODO: Add the AsRef trait appropriately as a trait bound.
fn char_counter<T:AsRef<str>>(arg: T) -> usize {arg.as_ref().chars().count()
}// Squares a number using as_mut().
// TODO: Add the appropriate trait bound.
fn num_sq<T:AsMut<u32>>(arg: &mut T) {// TODO: Implement the function body.let availableValue =arg.as_mut();(*availableValue)=(*availableValue).pow(2)
}#[cfg(test)]
mod tests {use super::*;#[test]fn different_counts() {let s = "Café au lait";assert_ne!(char_counter(s), byte_counter(s));}#[test]fn same_counts() {let s = "Cafe au lait";assert_eq!(char_counter(s), byte_counter(s));}#[test]fn different_counts_using_string() {let s = String::from("Café au lait");assert_ne!(char_counter(s.clone()), byte_counter(s));}#[test]fn same_counts_using_string() {let s = String::from("Cafe au lait");assert_eq!(char_counter(s.clone()), byte_counter(s));}#[test]fn mult_box() {let mut num: Box<u32> = Box::new(3);num_sq(&mut num);assert_eq!(*num, 9);}
}

90.一个完全蒙蔽的题目

GPT给我的答案

unsafe 关键字告诉编译器,这段代码可能包含不安全的操作,需要开发人员自己来确保其正确性和安全性。

  • let mut t:这是一个变量声明,声明了一个名为 t 的可变变量。t 的类型是 &mut u32,即一个可变的对 u32 类型的引用。

  • &mut *(address as *mut u32):这部分是一个复杂的表达式,用于将 address 强制类型转换为 *mut u32,然后进行解引用。具体来说:

    • address as *mut u32address 转换为一个 *mut u32 类型的指针。这个指针表示一个指向 u32 类型的可变内存地址。
    • &mut * 是解引用操作符,它将指针解引用,以获取指针指向的值。
  • *t = 0xAABBCCDD:这是将 t 所引用的内存位置设置为 0xAABBCCDD 的值。由于 t 是可变引用,因此可以通过 *t 来修改内存中的值

// tests5.rs
//
// An `unsafe` in Rust serves as a contract.
//
// When `unsafe` is marked on an item declaration, such as a function,
// a trait or so on, it declares a contract alongside it. However,
// the content of the contract cannot be expressed only by a single keyword.
// Hence, its your responsibility to manually state it in the `# Safety`
// section of your documentation comment on the item.
//
// When `unsafe` is marked on a code block enclosed by curly braces,
// it declares an observance of some contract, such as the validity of some
// pointer parameter, the ownership of some memory address. However, like
// the text above, you still need to state how the contract is observed in
// the comment on the code block.
//
// NOTE: All the comments are for the readability and the maintainability of
// your code, while the Rust compiler hands its trust of soundness of your
// code to yourself! If you cannot prove the memory safety and soundness of
// your own code, take a step back and use safe code instead!
//
// Execute `rustlings hint tests5` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONE/// # Safety
///
/// The `address` must contain a mutable reference to a valid `u32` value.
unsafe fn modify_by_address(address: usize) {// TODO: Fill your safety notice of the code block below to match your// code's behavior and the contract of this function. You may use the// comment of the test below as your format reference.unsafe {// todo!("Your code goes here")let mut t = &mut *(&mut *(address as *mut u32) as *mut u32); *t=0xAABBCCDD}
}#[cfg(test)]
mod tests {use super::*;#[test]fn test_success() {let mut t: u32 = 0x12345678;// SAFETY: The address is guaranteed to be valid and contains// a unique reference to a `u32` local variable.unsafe { modify_by_address(&mut t as *mut u32 as usize) };assert!(t == 0xAABBCCDD);}
}

 

相关文章:

RustDay06------Exercise[81-90]

81.宏函数里面的不同的匹配规则需要使用分号隔开 // macros4.rs // // Execute rustlings hint macros4 or use the hint watch subcommand for a // hint.// I AM NOT DONE#[rustfmt::skip] macro_rules! my_macro {() > {println!("Check out my macro!");};($…...

【Docker从入门到入土 6】Consul详解+Docker https安全认证(附证书申请方式)

Part 6 一、服务注册与发现的概念1.1 cmp问题1.2 服务注册与发现 二、Consul ----- 服务自动发现和注册2.1 简介2.2 为什么要用consul&#xff1f;2.3 consul的架构2.3 Consul-template 三、consul架构部署3.1 Consul服务器Step1 建立 Consul 服务Step2 查看集群信息Step3 通过…...

PCIe架构的处理器系统介绍

不同的处理器系统中&#xff0c;PCIe体系结构的实现方式不尽相同。PCIe体系结构以Intel的x86处理器为蓝本实现&#xff0c;已被深深地烙下x86处理器的印记。在PCIe总线规范中&#xff0c;有许多内容是x86处理器独有的&#xff0c;也仅在x86处理器的Chipset中存在。在PCIe总线规…...

国产内存强势崛起,光威龙武挑战D5内存24×2新标杆

今年国产内存的表现非常亮眼&#xff0c;出现了很多高质量的普惠产品&#xff0c;像是最近光威推出的一款内存条龙武ddr5 242就很有竞争力&#xff0c;加上之前神策新加入的ddr5 242版本&#xff0c;都是备受瞩目的新品&#xff0c;凭实力把DIY主机的内存配置拉高到了48GB。 龙…...

矩阵的运算

目标&#xff1a;实现一个能进行稀疏矩阵基本运算(包括加、减、乘)的运算器。 &#xff08;1&#xff09;以三元组顺序表表示稀疏矩阵&#xff0c;实现两个矩阵相加、相减、相乘的运算 &#xff08;2&#xff09;稀疏矩阵的输入形式为三元组表示&#xff0c;运算结果则以通常…...

Android 获取SIM卡号码权限申请

1.添加权限 在AndroidManifest.xml中添加如下权限 <uses-permission android:name"android.permission.READ_PHONE_STATE"/> 2.获取权限 如果你只在清单文件中添加权限却没有在代码中获取权限&#xff0c;代码还是会报错的。 报错原因&#xff1a; android…...

Linux CentOS 本地yum配置

本地开发用虚拟机&#xff0c;因为有光盘镜像在手&#xff0c;并不需要联网安装组件&#xff0c;只需要设置一下就可以让yum从本地获取源。 将安装盘挂载在合适位置 mount /dev/cdrom /mnt 进入目录 cd /etc/yum.repos.d/ 修改CentOS-Media.repo里面的挂载路径 …...

【c++速通】入门级攻略:什么是内联函数?函数重载又是什么?

&#x1f3a5; 屿小夏 &#xff1a; 个人主页 &#x1f525;个人专栏 &#xff1a; C入门到进阶 &#x1f304; 莫道桑榆晚&#xff0c;为霞尚满天&#xff01; 文章目录 &#x1f4d1;前言&#x1f324;️函数重载☁️函数重载的概念☁️函数重载的作用☁️C支持函数重载的原理…...

ubuntu 安装串口工具和添加虚拟串口

目录 一、串口工具安装 二、使用Windows本身虚拟的串口 &#xff08;一&#xff09;添加串口 1、保证虚拟机是关闭状态&#xff0c;打开“虚拟机设置”&#xff0c;点击“添加”。 2、选中“串行端口”&#xff0c;点击“完成”。 3、选中刚添加的串口&#xff0c;下拉选…...

【数据结构】数组和字符串(四):特殊矩阵的压缩存储:稀疏矩阵——三元组表

文章目录 4.2.1 矩阵的数组表示4.2.2 特殊矩阵的压缩存储a. 对角矩阵的压缩存储b~c. 三角、对称矩阵的压缩存储d. 稀疏矩阵的压缩存储——三元组表结构体初始化元素设置打印矩阵主函数输出结果代码整合 4.2.1 矩阵的数组表示 【数据结构】数组和字符串&#xff08;一&#xff…...

为什么POST请求经常发送两次?

大多数初级前端程序员&#xff0c;在通过浏览器F12的调试工具调试网络请求时&#xff0c;可能都会有一个发现&#xff0c;在进行POST请求时&#xff0c;明明代码里只请求了一次&#xff0c;为什么network里发送了两次呢&#xff0c;难道我代码出bug了&#xff1f;带着疑问点开第…...

打破总分行数据协作壁垒,DataOps在头部股份制银行的实践|案例研究

从银行开始建设数据仓库至今已近20年&#xff0c;当前各银行机构在数据能力建设中面临诸多困扰&#xff1a;如何保证数据使用时的准确性&#xff1f;如何让数据敏捷响应业务变化&#xff1f;如何让更多的业务人员使用数据&#xff1f; 这些问题极大影响了经营指标的达成与业务…...

测试用例的设计方法(全):边界值分析方法

一.方法简介 1.定义&#xff1a;边界值分析法就是对输入或输出的边界值进行测试的一种黑盒测试方法。通常边界值分析法是作为对等价类划分法的补充&#xff0c;这种情况下&#xff0c;其测试用例来自等价类的边界。 2.与等价划分的区别 1)边界值分析不是从某等价类中随便挑…...

酷开科技 | 酷开系统沉浸式大屏游戏更解压!

随着家庭娱乐需求日益旺盛&#xff0c;越来越多的家庭消费者和游戏玩家开始追求大屏游戏带来的沉浸感。玩家在玩游戏的时候用大屏能获得更广阔的视野和更出色的视觉包围感&#xff0c;因此用大屏玩游戏已经成为了一种潮流。用酷开系统玩大屏游戏&#xff0c;过瘾又刺激&#xf…...

读高性能MySQL(第4版)笔记20_Performance Schema和其他

1. 线程 1.1. MySQL服务端是多线程软件。它的每个组件都使用线程 1.2. 每个线程至少有两个唯一标识符 1.2.1. 操作系统线程ID 1.2.2. MySQL内部线程ID 2. 对象类型 2.1. OBJECT_TYPE列 2.2. EVENT 2.3. FUNCTION 2.4. PROCEDURE 2.5. TABLE 2.6. TRIGGER 3. Perfor…...

spring cloud Eureka集群模式搭建(IDEA中运行)《二》

上一篇集群配置文件完善 上一篇博客&#xff0c;想必大家都学会了Eureka集群模式的搭建和运行&#xff0c;针对上一篇的配置文件进行了优化&#xff0c;在这里分享给大家。上一篇主要有3个配置文件&#xff0c;分别对应3个不同的服务&#xff0c;这种形式配置文件分别写在了不…...

大模型(LLM)在电商推荐系统的探索与实践

本文对LLM推荐的结合范式进行了梳理和讨论&#xff0c;并尝试将LLM涌现的能力迁移应用在推荐系统之中&#xff0c;利用LLM的通用知识来辅助推荐&#xff0c;改善推荐效果和用户体验。 背景 电商推荐系统&#xff08;Recommend System&#xff0c;RecSys&#xff09;是一种基于…...

C语言之指针详解

目录 地址 指针的定义和使用 数组与指针的区别与联系 字符串与指针的用法 C 中的 NULL 指针 指针的算术运算 指向指针的指针 传递指针给函数 从函数返回指针 在学习指针之前&#xff0c;我们先弄清楚一个概念&#xff1a; 地址 地址在计算机内存中是一个唯一的标识符…...

【Java笔记+踩坑】设计模式——原型模式

导航&#xff1a; 【Java笔记踩坑汇总】Java基础JavaWebSSMSpringBootSpringCloud瑞吉外卖/黑马旅游/谷粒商城/学成在线设计模式面试题汇总性能调优/架构设计源码-CSDN博客​ 目录 零、经典的克隆羊问题&#xff08;复制10只属性相同的羊&#xff09; 一、传统方案&#xff1…...

Flutter GetX使用详解

介绍 GetX是一款功能强大且轻量级的Flutter状态管理和路由管理库。它提供了一种简单而强大的方式来构建Flutter应用程序&#xff0c;无需大量的模板代码。GetX不仅提供了状态管理和路由管理&#xff0c;还包括其他实用工具&#xff0c;如国际化和依赖注入。 在本文中&#xf…...

【ARM Coresight 系列文章 3.3 - ARM Coresight SWD 协议详细介绍】

文章目录 1.1 SWD 协议框图1.2 读/写时序及命令1.2.1 SWD 时序1.2.2 SWD 命令详情1.3 芯片探测1.3.1 获取芯片 ID1.4 读/写操作1.1 SWD 协议框图 SWD协议可以配置SoC内部几乎所有的寄存器。时钟信号由SWCLK 管脚输入,数据信号从SWDIO管脚输入输出。首先 HOST 对SW-DP 进行操作…...

作为开发者,可视化开发工具了解一下

你是否为编程世界的各种挑战感到头痛&#xff1f;想要以更高效、简单的方式开发出专业级的项目&#xff1f; JNPF低代码工具正是你苦心寻找的产品&#xff01;它是一款专为稍微懂一点点编程思想的入门级人员设计的神奇工具&#xff0c;集成了丰富的功能和组件&#xff0c;让你轻…...

Python:实现日历功能

背景 日常生活中&#xff0c;每天都要用到日历&#xff0c;日历成为我们生活中的必需品&#xff0c;那么如何制作日历呢&#xff0c;其实方法有很多&#xff0c;可以直接在excel中制作&#xff0c;也可以手画等等。 学习过编程的朋友&#xff0c;能否想到用Python编写一…...

2.9.C++项目:网络版五子棋对战之业务处理模块的设计

文章目录 一、意义二、功能三、管理&#xff08;一&#xff09;客户端请求&#xff08;二&#xff09;websocket 四、框架五、完整代码 一、意义 将所有的模块整合在一起&#xff0c;通过网络通信获取到客户端的请求&#xff0c;提供不同的业务处理。 服务器模块&#xff0c;是…...

springboot actuator 常用接口

概述 微服务作为一项在云中部署应用和服务的新技术是当下比较热门话题&#xff0c;而微服务的特点决定了功能模块的部署是分布式的&#xff0c;运行在不同的机器上相互通过服务调用进行交互&#xff0c;业务流会经过多个微服务的处理和传递&#xff0c;在这种框架下&#xff0…...

知识点滴 - Email地址不区分大小写

电子邮件地址本身对字符大小写不敏感。这意味着实际的电子邮件地址&#xff0c;如 "exampleemail.com"&#xff0c;并不区分字母的大小写。无论你输入的是大写字母还是小写字母&#xff0c;它仍然会到达同一个电子邮件账户。例如&#xff0c;如果您的电子邮件地址是 …...

同一个页面同一区域两个el-table在v-if下样式重叠问题

&#x1f349;正常情况下在radio切换时两个表格的样式应如下 &#x1f349;实际上用v-if显示时会出现以下问题&#xff08;本该属于时间段相同模块的表格却出现在时间段自定义的表格中&#xff09; &#x1f349;解决方案&#xff1a; &#x1f343;一、将v-if替换成v-show(…...

ExoPlayer架构详解与源码分析(6)——MediaPeriod

系列文章目录 ExoPlayer架构详解与源码分析&#xff08;1&#xff09;——前言 ExoPlayer架构详解与源码分析&#xff08;2&#xff09;——Player ExoPlayer架构详解与源码分析&#xff08;3&#xff09;——Timeline ExoPlayer架构详解与源码分析&#xff08;4&#xff09;—…...

【开题报告】基于Spring Boot的课程在线预约系统的设计与实现

1.引言 随着互联网的发展&#xff0c;线上教育和课程培训变得越来越普遍。然而&#xff0c;很多学生在选择课程时面临一些困扰&#xff0c;例如如何找到适合自己的课程&#xff0c;如何与老师进行预约等。因此&#xff0c;设计一个基于Spring Boot的课程在线预约系统具有重要的…...

React Hooks还有哪些常用的用法?

除了之前提到的 useState、useEffect、useContext、useRef、useMemo 和 useCallback,还有一些其他常用的 React Hooks,它们提供了额外的功能和灵活性。以下是其中一些常见的 React Hooks: 1:useReducer:用于在函数组件中管理复杂的状态逻辑,类似于 Redux 的 reducer。 …...