Skip to content

Error when using optional reference fields #25798

Description

@squidink7

Describe the bug

When a struct (Program in the example below) has a field (FooHolder) that has an optional reference to another struct (Foo) that has a reference field, V gives an error saying the reference field must be initialized. Given that its behind an optional and should be initialized to none the reference field wouldn't exist, let alone need to be initialized.

Reproduction Steps

struct Foo {
	data &int
}

struct FooHolder {
	foo ?&Foo
}

struct Program {
	foo_holder FooHolder
}

fn main() {
	p := Program{}
}

Expected Behavior

To run without error

Current Behavior

main.v:14:7: error: reference field `Program.foo_holder.foo.data` must be initialized (part of struct `Foo`)
   12 | 
   13 | fn main() {
   14 |     p := Program{}
      |          ~~~~~~~~~
   15 | }

Possible Solution

No response

Additional Information/Context

You can work around this error by manually initializing FooHolder like so

struct Foo {
	data &int
}

struct FooHolder {
	foo ?&Foo
}

struct Program {
	foo_holder FooHolder = FooHolder{}
}

fn main() {
	p := Program{}
	println(p.foo_holder.foo) // &Option(&nil)
}

V version

V 0.4.12 73cc802

Environment details (OS name and version, etc.)

V full version V 0.4.12 3555998.73cc802
OS linux, "Linux"
Processor 12 cpus, 64bit, little endian, AMD Ryzen 5 7640U w/ Radeon 760M Graphics
Memory 0.66GB/14.93GB
V executable /home/sirsegv/.v/v
V last modified time 2025-11-21 03:15:25
V home dir OK, value: /home/sirsegv/.v
VMODULES OK, value: /home/sirsegv/.vmodules
VTMP OK, value: /tmp/v_1000
Current working dir OK, value: /home/sirsegv
Git version git version 2.52.0
V git status weekly.2024.39-2483-g73cc8022
.git/config present true
cc version cc (GCC) 15.2.1 20251112
gcc version gcc (GCC) 15.2.1 20251112
clang version clang version 21.1.5
tcc version tcc version 0.9.28rc 2025-02-13 HEAD@f8bd136d (x86_64 Linux)
tcc git status thirdparty-linux-amd64 696c1d84
emcc version N/A
glibc version ldd (GNU libc) 2.42

Note

You can use the 👍 reaction to increase the issue's priority for developers.

Please note that only the 👍 reaction to the issue itself counts as a vote.
Other reactions and those to comments will not be taken into account.

Metadata

Metadata

Assignees

Labels

BugThis tag is applied to issues which reports bugs.Status: ConfirmedThis bug has been confirmed to be valid by a contributor.Unit: CheckerBugs/feature requests, that are related to the type checker.

Type

No fields configured for Bug.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions