newtype-sized #493
Replies: 2 comments
-
第1题 - use std::fmt;
/* Define the Wrapper type */
struct Wrapper(Vec<String>);
// Display is an external trait
impl fmt::Display for Wrapper {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}]", self.0.join(", "))
}
}
fn main() {
// Vec is an external type, so you cannot implement Display trait on Vec type
let w = Wrapper(vec![String::from("hello"), String::from("world")]);
println!("w = {}", w);
} 第2题 - impl /* Make it workd */
struct Meters(u32);
impl Meters {
fn pow(self, times: u32) -> u32 {
let mut res = 1;
for _ in 0..times {
res *= self.0
}
res
}
}
fn main() {
let i: u32 = 2;
assert_eq!(i.pow(2), 4);
let n = Meters(i);
// The `pow` method is defined on `u32` type, we can't directly call it
assert_eq!(n.pow(2), 4);
} 第3题 - 没明白啥意思
第4题 - use std::fmt::{self, format};
use std::ops::Add;
struct Meters(u32);
impl fmt::Display for Meters {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "There are still {} meters left", self.0)
}
}
impl Add for Meters {
type Output = Self;
fn add(self, other: Meters) -> Self {
Self(self.0 + other.0)
}
}
fn main() {
let d = calculate_distance(Meters(10), Meters(20));
assert_eq!(format!("{}", d), "There are still 30 meters left");
println!("d:{}", d);
}
/* Implement calculate_distance */
fn calculate_distance(adder: Meters, added: Meters) -> Meters {
adder + added
} 第5题 type Operations = VeryVerboseEnumOfThingsToDoWithNumbers; 第6题 - Self enum VeryVerboseEnumOfThingsToDoWithNumbers {
Add,
Subtract,
}
impl VeryVerboseEnumOfThingsToDoWithNumbers {
fn run(&self, x: i32, y: i32) -> i32 {
match self {
Self::Add => x + y,
Self::Subtract => x - y,
}
}
}
fn main() {} 第7题 /* Make it work with const generics */
fn my_function<const N: usize>() -> [u32; N] {
[123; N]
}
fn main() {
let arr = my_function::<2>();
println!("{:?}", arr);
} 第8题 - slice reference /* Make it work with slice references */
fn main() {
let s: &str = "Hello there!";
let arr: [u8; 3] = [1, 2, 3];
// &[u8] is a slice ref, &[u8; 3] is ref to an array
let arr_slice: &[u8] = &arr;
} 第9题 - trait object /* Make it work in two ways */
use std::fmt::Display;
fn foobar(thing: Box<dyn Display>) {}
fn main() {} |
Beta Was this translation helpful? Give feedback.
0 replies
-
答案:https://github.com/sunface/rust-by-practice/blob/master/solutions/newtype-sized.md |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
newtype-sized
Learn Rust with Example, Exercise and real Practice, written with ❤️ by https://course.rs team
https://practice.course.rs/newtype-sized.html
Beta Was this translation helpful? Give feedback.
All reactions