HiveBrain v1.2.0
Get Started
← Back to all entries
gotcharustCritical

Why does the println! function use an exclamation mark in Rust?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
printlnfunctionwhyusethemarkdoesrustexclamation

Problem

In Swift, ! means to unwrap an optional (possible value).

Solution

println! is not a function, it is a macro. Macros use ! to distinguish them from normal method calls. The documentation contains more information.

See also:

  • What is the difference between macros and functions in Rust?



Rust uses the Option type to denote optional data. It has an unwrap method.

Rust 1.13 added the question mark operator ? as an analog of the try! macro (originally proposed via RFC 243).

An excellent explanation of the question mark operator is in The Rust Programming Language.

fn foo() -> Result {
    Ok(4)
}

fn bar() -> Result {
    let a = foo()?;
    Ok(a + 4)
}


The question mark operator also extends to Option, so you may see it used to unwrap a value or return None from the function. This is different from just unwrapping as the program will not panic:

fn foo() -> Option {
    None
}

fn bar() -> Option {
    let a = foo()?;
    Some(a + 4)
}

Code Snippets

fn foo() -> Result<i32, Error> {
    Ok(4)
}

fn bar() -> Result<i32, Error> {
    let a = foo()?;
    Ok(a + 4)
}
fn foo() -> Option<i32> {
    None
}

fn bar() -> Option<i32> {
    let a = foo()?;
    Some(a + 4)
}

Context

Stack Overflow Q#29611387, score: 145

Revisions (0)

No revisions yet.