这个例子展示了一种在 Rust 中处理不同类型消息的优雅方式。它有 4 个变体,一些变体具有子成员,只有在枚举属于该特定类型时才能访问这些子成员。在 TypeScript 中也可以使用类似的模式。
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
Run Code Online (Sandbox Code Playgroud)
在 C++ 中,这很可能与以下代码进行比较。
struct Message
{
enum MessageType {QUIT, MOVE, WRITE, CHANGECOLOR} type;
union MessageContent
{
struct Move { int x; int y;} move;
std::string write;
std::tuple<int, int, int> changeColor;
} content;
};
Run Code Online (Sandbox Code Playgroud)
但是,这种方式不是类型安全的,并且内存管理会变得混乱(例如,Message如果MessageTypeis被破坏,则确保字符串被释放WRITE)。在现代 C++ 中执行此操作的最佳方法是什么?
考虑这段代码来读取 rust 中的用户输入
use std::io;
fn main() {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("error: unable to read user input");
println!("{}", input);
}
Run Code Online (Sandbox Code Playgroud)
为什么没有办法这样做?
use std::io;
fn main() {
let mut input = io::stdin()
.read_line()
.expect("error: unable to read user input");
println!("{}", input);
}
Run Code Online (Sandbox Code Playgroud)
其他语言会更方便