Skip to content

Recursive struct with optional fails to compile #7633

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
BinaryWarlock opened this issue Jan 1, 2021 · 1 comment
Closed

Recursive struct with optional fails to compile #7633

BinaryWarlock opened this issue Jan 1, 2021 · 1 comment
Labels
question No questions on the issue tracker, please.
Milestone

Comments

@BinaryWarlock
Copy link

I don't know if this is a dupe of #2746 or simply related, or even intended behavior, but a recursive struct type with an optional:

const Foo = struct {
    nested: ?Foo,
};

Fails to compile with:

error: struct 'Foo' depends on itself

However, using an optional pointer:

const Foo = struct {
    nested: ?*Foo,
};

Works.

Is my understanding correct that in Zig ?T on a struct type should be equivalent (at least internally) to a nullable pointer to T? If that's the case then I don't know why the first case fails since they should be equivalent.

I was hoping I could just build these Foo values on the stack and nest them and return them, but even if this compiled would that be legal behavior? (i.e. would copy elision take over and construct the whole hierarchy on the caller's stack?)

For example:

fn f() Foo {
    var ret = Foo { .nested=null; };
    return Foo { .nested=ret };
}

Would this be sane?

@ghost
Copy link

ghost commented Jan 1, 2021

No, optionals are not pointers. They are values plus an "is null" bit, so the struct you propose would have infinite size.

@daurnimator daurnimator added the question No questions on the issue tracker, please. label Jan 1, 2021
@andrewrk andrewrk added this to the 0.8.0 milestone Jan 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question No questions on the issue tracker, please.
Projects
None yet
Development

No branches or pull requests

3 participants