It looks we can't declare methods for ?T types. Any bad to prevent this?

const T = struct {
   pub fn foo(t: ?T) void {
       _ = t;

pub fn main() !void {
	var t: ?T = null;; // works; // not work

I don’t think so, you should generally prefer to check optional for null before doing anything with it.

As @tensorush says, you have to check if the optional is null or not before you can do anything with it first. You can unwrap it unconditionally (which would error if it’s null):


or conditionally, where inside the body of the if , not_null_t is guaranteed to not be null:

if (t) |not_null_t| {;

Here’s the problem:

Optional(T) is a type itself, it is not the same type as T.

The member function that you have defined is in the scope of T. However, you are trying to call it on Optional(T).

To clarify this, imagine you have a type Array(T). Let’s say that T has a member function Foo. Array(T).Foo doesn’t mean anything because Array(T) doesn’t have foo - T does. So you could say:

Array(T)[0].Foo() // call foo on the zero element (which is a type T)

But it doesn’t make sense to say:

Array(T).Foo() // Foo doesn't belong to Array(T), it belongs to elements T

Applying this same logic:

Optional(T).?.Foo() // call Foo on the unwrapped value of type T

Where as:

Optional(T).Foo() // Foo doesn't belong to Optional(T), it belongs to value T
1 Like