#How to call method from optional pointer?

1 messages · Page 1 of 1 (latest)

dense adder
#

Like

const Foo = struct {
  pub fn bar(self: *Foo) i32 {
  return 42;
  }
};

var some: ?*Foo = null;
// ... assign somewhere

pub fn other() {
   const something = some.bar() orelse 0;

obviously would not work
const something = (some orelse 0).bar(); also would not

plain trench
#

you can do either:

some.?.bar();

or:

if (some) |s| s.bar() else 0;
#

the top one will fail if it isn't defined so i dont recommend that in your usecase

#

the bottom one is what you want