wnw231423's blog

Reason the world.

Rust to modern C++ 02: Enums and Smart Pointers

发布于 # C++

前言: 本文章主要用于个人学习记录. 我学习过Rust, 接触过现代C++代码, 但未做系统性学习, 本文章尝试做一些学习梳理. 如有错误, 欢迎批评指正. 参考资料: Effective Modern C++ Enums and Smart Pointers Enums 参考 Effective Modern C++ Item 10. Rust的Enum和OCaml中的Variant非常相似,功能强大且支持模式匹配。 enum Message { Quit, Move {x: i32, y: i32}, Write(String), ChangeColor(i32, i32, i32) } 而C++中的Enum则没有这么强大的功能。首先,C++98 风格的Enum被称为unscoped enums, 因为enum中定义的变量会“溢出”到作用域中来,例如: enum Col

Rust to modern C++ 01: `auto`, `const` & Uniform Initialization

发布于 # C++

前言: 本文章主要用于个人学习记录. 我学习过Rust, 接触过现代C++代码, 但未做系统性学习, 本文章尝试做一些学习梳理. 如有错误, 欢迎批评指正. 参考资料: Effective Modern C++. let mut x = 42; const CONSTANT: i32 = 42; let hello = String::from("Hello, world!"); let vec: Vec<_> = vec![1, 2, 3]; 对于以上最基础的Rust代码,我们可以找出很多东西。Rust有类型推断,这意味着我们在很多情况下可以省略类型标注;在Rust中,变量通常是immutable的,需要我们显示地去标注mut;Rust有许多方法来初始化一个变量,既可以借助一个struct中的method去构造,也可以使用宏直接构造一个已经包含某些元素的vector。