Sisu
E0062

Optional used as if it were present

ErrorUnsafe fix

Built from the repository at commit a8614dc.

A field read, a method call, an index or a for needs a value, not an optional of one. An optional may be None, which has no fields, methods or elements.

Why

Sisu has no null pointer errors at runtime: the checker makes the program say what happens when the optional is None. ?. reads the member only when the optional holds a value, and gives None otherwise. if let runs a block with the value only when it is present.

An optional of an optional, such as a Node??, has two layers, and ?. takes only one off: n?.value on a Node?? reads value from a Node?, which may be None too. Peel the other layer first with ??: (n ?? None)?.value.

Broken

class Node {
    value: i64
    next: Node?
}

fn second(n: Node) -> i64 {
    n.next.value
}

fn main() {
    print(second(Node(value: 1, next: Node(value: 2, next: None))))
}

What sisu says

error[E0062]: `n.next` may be `None`
 --> E0062.sisu:7:5
  |
7 |     n.next.value
  |     ^^^^^^
  |
  = help: to use the value only when it is present, unwrap it with `if let`
help: if a `None` result is fine, use `?.`
  |
7 |     n.next?.value
  |           +

sisu: 1 error
sisu: for more on a code, run `sisu explain <code>`: E0062

Fixed

class Node {
    value: i64
    next: Node?
}

fn second(n: Node) -> i64 {
    if let next = n.next {
        next.value
    } else {
        0
    }
}

fn main() {
    print(second(Node(value: 1, next: Node(value: 2, next: None))))
}

Related

  • E0049: ?. on a value that is not optional.