Skip to content

Unwrapped optional aliasing footgun #2915

@ghost

Description

const std = @import("std");

const Thing = struct {
    initial_sample: ?usize,
};

pub fn main() void {
    var thing = Thing {
        .initial_sample = 3,
    };

    if (thing.initial_sample) |t| {
        std.debug.warn("before: {}\n", t); // prints 3

        thing.initial_sample = null;

        std.debug.warn("after: {}\n", t); // prints 0
    }
}

This should print 3 both times. Also,

    if (thing.initial_sample) |t| {
        std.debug.warn("before: {}\n", t); // prints 3

        thing.initial_sample = 2;

        std.debug.warn("after: {}\n", t); // prints 2
    }

I think this broke some time in the past month. (It manifested as a noticeable runtime bug in my game project.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status

    Done

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions