Skip to content

Is it possible to explicitly set a struct pointer to null? #598

Description

@undefinedmaniac

I am trying to make a struct field optional by using the null pointer state to represent that the value is not present (this is mentioned in the Cap'n Proto FAQ under "How do I make a field optional?").

Using this schema as an example:

struct Foo {}

struct Bar {
    inner @0 :Foo;
}

struct MyUnion {
    union {
        none @0 :Void;
        some @1 :Foo;
    }
}

Is there a way to create an instance of Bar with inner explicitly set to null? E.g.

let mut root = builder.init_root::<example_capnp::bar::Builder>();
root.set_inner(None); // does not work

If I omit all calls to init_inner/set_inner, the default value is null, however this creates a problem for union types. Imagine I want to create an instance of MyUnion with variant some and Foo set to null.

let mut root = builder.init_root::<example_capnp::my_union::Builder>();

// Required to set the union variant to 'some', but also initializes the pointer so that Foo is not null
let some = root.reborrow().init_some();

// I would like a way to call init_some() without making has_some() == true
assert!(root.has_some())

Ideally, on the receiver side I would be able to do something like:

if let Which::Some(r) = reader.reborrow().which().unwrap() {
    if reader.has_some() {
        // Struct is set to a value
    } else {
        // Struct is 'not present'
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions