Type Aliases Name Common Types

Give verbose types readable names with plain and generic aliases — no new type is created, so aliases stay interchangeable with the original.

RustData Integrity

Code

rustsnippet
29 lines
// type alias:给类型起可读的名字,不产生新类型,可与原类型互换
type Meters = u64;
type Payload = Vec<u8>;

// 泛型别名:常见于把 Result 缩短为库内错误约定
type ParseResult<T> = Result<T, String>;

fn distance(a: Meters, b: Meters) -> Meters {
    if a > b { a - b } else { b - a }
}

fn parse_port(text: &str) -> ParseResult<u16> {
    text.parse::<u16>().map_err(|e| e.to_string())
}

fn main() {
    let route: Meters = 4_800;
    // alias 与原类型完全等价:u64 的值可以直接赋给 Meters
    let raw: u64 = route;
    println!("distance: {}", distance(route, raw));

    let frames: Vec<Payload> = vec![vec![1, 2], vec![3]];
    println!("frames: {}", frames.len());

    match parse_port("8080") {
        Ok(port) => println!("port {port}"),
        Err(msg) => println!("bad port: {msg}"),
    }
}

What the code does

The working surface is the functions distance, parse_port and main — everything else is wiring.

Fallible operations return Result, forcing the caller to handle both arms explicitly. A match spells out every case; omit one and the code does not compile.

Watch out for

  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

The main signature reads fn distance(a: Meters, b: Meters) -> Meters

Running the file prints labeled results such as distance:, frames:, port — each operation’s effect is visible in the output.

The entry point wires distance and parse_port together — run it once and the whole demo flows.

Key statements

fn parse_port(text: &str) -> ParseResult<u16> {
text.parse::<u16>().map_err(|e| e.to_string())
}
fn distance(a: Meters, b: Meters) -> Meters {
if a > b { a - b } else { b - a }
}
match parse_port("8080") {
Ok(port) => println!("port {port}"),
Err(msg) => println!("bad port: {msg}"),
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
Through `Result` values. Nothing panics inside the snippet; the caller decides how to handle each failure.
What does Type Aliases Name Common Types print when run?
Run it as a complete program — the output lines carry labels such as `distance:`, `frames:`, `port`.