advance/into-types/custom-type #700
Replies: 11 comments 7 replies
-
_ => panic!("不合规定的值:{}", i)这个还是没看懂 |
Beta Was this translation helpful? Give feedback.
-
Newtype 是一个源自~~(U.C.0079,逃)~~Haskell 编程语言的概念。 |
Beta Was this translation helpful? Give feedback.
-
“panic 的返回值是 !,代表它决不会返回任何值,既然没有任何返回值,那自然不会存在分支类型不匹配的情况。” |
Beta Was this translation helpful? Give feedback.
-
scala那里憋不住了 |
Beta Was this translation helpful? Give feedback.
-
永不返回参考Scala的Nothing。 因为Nothing是任何对象的子类,返回Nothing的函数可以在match的分支上兼容其他任何类型。 (为Scala叹息) |
Beta Was this translation helpful? Give feedback.
-
也可以这样理解,!是所有类型的子类型 |
Beta Was this translation helpful? Give feedback.
-
"隐藏内部类型的细节"一节提到, // ...
let n = Meters(i);
// 下面的代码将报错,因为`Meters`类型上没有`pow`方法
// assert_eq!(n.pow(2), 4);
}
如果在定义 https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html 这篇文章,“Advantages”一节,最后一句写到:
我试了一下, // mymod.rs
pub struct Meters(u32);
impl Meters {
pub fn new(v: u32) -> Self { // 若没有new()方法,note: constructor is not visible here due to private fields
Meters(v)
}
} // main.rs
pub mod mymod;
use mymod::Meters;
fn main() {
let i: u32 = 2;
assert_eq!(i.pow(2), 4);
let n = Meters::new(i);
// 下面的代码将报错,因为`Meters`类型上没有`pow`方法
// assert_eq!(n.pow(2), 4);
assert_eq!(n.0.pow(2), 4); // error[E0616]: field `0` of struct `Meters` is private
} |
Beta Was this translation helpful? Give feedback.
-
advance/into-types/custom-type
https://course.rs/advance/into-types/custom-type.html
Beta Was this translation helpful? Give feedback.
All reactions