type-conversions/from-into #212
Replies: 10 comments 3 replies
-
这节练习题对应的讲解在哪儿啊?我怎么没找到 |
Beta Was this translation helpful? Give feedback.
-
/* // 使用两种方式修复错误 let i3: u32 = 'a'.into(); // 使用两种方法来解决错误 println!("Success!") /* #[derive(Debug)] impl From for Number { // 填空
} /* enum CliError { impl Fromio::Error for CliError { impl Fromnum::ParseIntError for CliError { fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> { fn main() { /* fn main() {
} #[derive(Debug, PartialEq)] impl TryFrom for EvenNum {
} fn main() {
} |
Beta Was this translation helpful? Give feedback.
-
第1题fn main() {
// impl From<bool> for i32
let i1:i32 = false.into();
let i2:i32 = i32::from(false);
assert_eq!(i1, i2);
assert_eq!(i1, 0);
// 使用两种方式修复错误
// 1. 哪个类型实现 From 特征 : impl From<char> for ? , 你可以查看一下之前提到的文档,来找到合适的类型
// 2. 上一章节中介绍过的某个关键字
let i3: i32 = 'a' as i32;
unsafe {
let i3: i32 = std::mem::transmute_copy::<char, i32>(&'a');
}
// 使用两种方法来解决错误
let s: String = 'a'.into();
let s: String = String::from('a');
println!("Success!")
} 第2题// From 被包含在 `std::prelude` 中,因此我们没必要手动将其引入到当前作用域来
// use std::convert::From;
#[derive(Debug)]
struct Number {
value: i32,
}
impl From<i32> for Number {
// 实现 `from` 方法
fn from(value: i32) -> Self {
Self {
value
}
}
}
// 填空
fn main() {
let num = Number{ value: 30 };
assert_eq!(num.value, 30);
let num: Number = 30_i32.into();
assert_eq!(num.value, 30);
println!("Success!")
} 第3题use std::fs;
use std::io;
use std::num;
#[derive(Debug)]
enum CliError {
IoError(io::Error),
ParseError(num::ParseIntError),
}
impl From<io::Error> for CliError {
// 实现 from 方法
fn from(src: io::Error) -> Self {
Self::IoError(src)
}
}
impl From<num::ParseIntError> for CliError {
// 实现 from 方法
fn from(src: num::ParseIntError) -> Self {
Self::ParseError(src)
}
}
fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
// ? 自动将 io::Error 转换成 CliError
let contents = fs::read_to_string(&file_name)?;
// num::ParseIntError -> CliError
let num: i32 = contents.trim().parse()?;
Ok(num)
}
fn main() {
match open_and_parse_file("abc") {
Ok(num) => println!("ok, {}", num),
Err(e) => println!("err: {:?}", e),
}
println!("Success!")
} 第4题// TryFrom 和 TryInto 也被包含在 `std::prelude` 中, 因此以下引入是没必要的
// use std::convert::TryInto;
fn main() {
let n: i16 = 256;
// Into 特征拥有一个方法`into`,
// 因此 TryInto 有一个方法是 ?
let n: u8 = match n.try_into() {
Ok(n) => n,
Err(e) => {
println!("there is an error when converting: {:?}, but we catch it", e.to_string());
0
}
};
assert_eq!(n, 0);
println!("Success!")
} 第5题#[derive(Debug, PartialEq)]
struct EvenNum(i32);
impl TryFrom<i32> for EvenNum {
type Error = ();
// 实现 `try_from`
fn try_from(value: i32) -> Result<Self, Self::Error> {
if value % 2 == 0 {
Ok(EvenNum(value))
} else {
Err(())
}
}
}
fn main() {
assert_eq!(EvenNum::try_from(8), Ok(EvenNum(8)));
assert_eq!(EvenNum::try_from(5), Err(()));
// 填空
let result: Result<EvenNum, ()> = 8i32.try_into();
assert_eq!(result, Ok(EvenNum(8)));
let result: Result<EvenNum, ()> = 5i32.try_into();
assert_eq!(result, Err(()));
println!("Success!")
} |
Beta Was this translation helpful? Give feedback.
-
原来into()方法和From特征有这样的关系啊!顿悟了!前面老纳闷into()方法怎么转啥都行...就是需要显式指定类型 |
Beta Was this translation helpful? Give feedback.
-
第一题fn main() {
// impl From<bool> for i32
let i1:i32 = false.into();
let i2:i32 = i32::from(false);
assert_eq!(i1, i2);
assert_eq!(i1, 0);
// 使用两种方式修复错误
// 1. 哪个类型实现 From 特征 : impl From<char> for ? , 你可以查看一下之前提到的文档,来找到合适的类型
// 2. 上一章节中介绍过的某个关键字
let i3: i32 = 'a' as i32;
unsafe {
let i3: i32 = std::mem::transmute_copy::<char, i32>(&'a');
}
// 使用两种方法来解决错误
let s: String = 'a'.into();
let s: String = String::from('a');
println!("Success!")
} 第二题// From 被包含在 `std::prelude` 中,因此我们没必要手动将其引入到当前作用域来
// use std::convert::From;
#[derive(Debug)]
struct Number {
value: i32,
}
impl From<i32> for Number {
fn from(v: i32) -> Number{
Number{
value: v,
}
}
}
// 填空
fn main() {
let num = Number::from(30);
assert_eq!(num.value, 30);
let num: Number = Number{value:30};
assert_eq!(num.value, 30);
println!("Success!")
} 第三题use std::fs;
use std::io;
use std::num;
enum CliError {
IoError(io::Error),
ParseError(num::ParseIntError),
}
impl From<io::Error> for CliError {
fn from(err: io::Error) -> Self{
CliError::IoError(err)
}
}
impl From<num::ParseIntError> for CliError {
fn from(err: num::ParseIntError) -> CliError{
CliError::ParseError(err)
}
}
fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
// ? 自动将 io::Error 转换成 CliError
let contents = fs::read_to_string(&file_name)?;
// num::ParseIntError -> CliError
let num: i32 = contents.trim().parse()?;
Ok(num)
}
fn main() {
println!("Success!")
} 第四题// TryFrom 和 TryInto 也被包含在 `std::prelude` 中, 因此以下引入是没必要的
// use std::convert::TryInto;
fn main() {
let n: i16 = 256;
// Into 特征拥有一个方法`into`,
// 因此 TryInto 有一个方法是 ?
let n: u8 = match n.try_into() {
Ok(n) => n,
Err(e) => {
println!("there is an error when converting: {:?},
but we catch it", e.to_string());
0
}
};
assert_eq!(n, 0);
println!("Success!")
} 第五题#[derive(Debug, PartialEq)]
struct EvenNum(i32);
impl TryFrom<i32> for EvenNum {
type Error = ();
// 实现 `try_from`
fn try_from(value: i32) -> Result<Self, Self::Error> {
if value % 2 == 0 {
Ok(EvenNum(value))
} else {
Err(())
}
}
}
fn main() {
assert_eq!(EvenNum::try_from(8), Ok(EvenNum(8)));
assert_eq!(EvenNum::try_from(5), Err(()));
// 填空
let result: Result<EvenNum, ()> = 8i32.try_into();
assert_eq!(result, Ok(EvenNum(8)));
let result: Result<EvenNum, ()> = 5i32.try_into();
assert_eq!(result, Err(()));
println!("Success!")
} |
Beta Was this translation helpful? Give feedback.
-
mark finished |
Beta Was this translation helpful? Give feedback.
-
第一题#[warn(unused_variables)]
fn main() {
// impl From<bool> for i32
let i1: i32 = false.into(); // i1 = 0
let i2: i32 = i32::from(false); // i2 = 0
assert_eq!(i1, i2);
assert_eq!(i1, 0);
// 使用两种方式修复错误
// 1. 哪个类型实现 From 特征 : impl From<char> for u32/u64/u128/String , 你可以查看一下之前提到的文档,来找到合适的类型
// 2. 上一章节中介绍过的某个关键字
let i3: i32 = u32::from('a') as i32; // 使用内置From实现char->u32
// 使用两种方法来解决错误
// let s: String = String::from('a');
let s: String = 'a'.into();
println!("Success!")
} 第二题// From 被包含在 `std::prelude` 中,因此我们没必要手动将其引入到当前作用域来
// use std::convert::From;
#[derive(Debug)]
struct Number {
value: i32,
}
impl From<i32> for Number { // 为Number实现From
fn from(num: i32) -> Self { // 返回一个Number/Self类型
Self { // 定义Number,并进行值绑定
value: num
}
}
}
// 填空
fn main() {
let num = Number::from(30);
assert_eq!(num.value, 30);
let num: Number = 30.into();
assert_eq!(num.value, 30);
println!("Success!")
} 第三题use std::fs;
use std::io;
use std::num;
enum CliError {
IoError(io::Error),
ParseError(num::ParseIntError),
}
impl From<io::Error> for CliError {
fn from(e: io::Error) -> Self{
CliError::IoError(e)
}
}
impl From<num::ParseIntError> for CliError {
fn from(e: num::ParseIntError) -> Self {
CliError::ParseError(e)
}
}
fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
// ? 自动将 io::Error 转换成 CliError
let contents = fs::read_to_string(&file_name)?;
// num::ParseIntError -> CliError
let num: i32 = contents.trim().parse()?;
Ok(num)
}
fn main() {
println!("Success!")
} 第四题// TryFrom 和 TryInto 也被包含在 `std::prelude` 中, 因此以下引入是没必要的
// use std::convert::TryInto;
fn main() {
let n: i16 = 256;
// Into 特征拥有一个方法`into`,
// 因此 TryInto 有一个方法是 'try_into'
let n: u8 = match n.try_into() {
Ok(n) => n,
Err(e) => {
println!("there is an error when converting: {:?}, but we catch it", e.to_string());
0
}
};
assert_eq!(n, 0);
println!("n = {}", n);
println!("Success!")
} 第五题#[derive(Debug, PartialEq)]
struct EvenNum(i32);
impl TryFrom<i32> for EvenNum {
type Error = (); // 关联类型
// 实现 `try_from`
fn try_from(value: i32) -> Result<Self, Self::Error> {
if value % 2 == 0 {
Ok(EvenNum(value))
} else {
Err(())
}
}
}
fn main() {
assert_eq!(EvenNum::try_from(8), Ok(EvenNum(8)));
assert_eq!(EvenNum::try_from(5), Err(()));
// 填空
let result: Result<EvenNum, ()> = 8i32.try_into();
assert_eq!(result, Ok(EvenNum(8)));
let result: Result<EvenNum, ()> = 5i32.try_into();
assert_eq!(result, Err(()));
println!("Success!")
} |
Beta Was this translation helpful? Give feedback.
-
Day 10 |
Beta Was this translation helpful? Give feedback.
-
type-conversions/from-into
Learning Rust By Practice, narrowing the gap between beginner and skilled-dev with challenging examples, exercises and projects.
https://zh.practice.rs/type-conversions/from-into.html
Beta Was this translation helpful? Give feedback.
All reactions