# Is there a way call a method shared by all union field types?

**URL:** <https://ziggit.dev/t/is-there-a-way-call-a-method-shared-by-all-union-field-types/1288>\
**Category:** Help\
**Tags:** language\
**Created:** [July 27, 2023, 9:24am UTC](https://ziggit.dev/t/is-there-a-way-call-a-method-shared-by-all-union-field-types/1288 "2023-07-27T09:24:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![zigo](https://ziggit.dev/user_avatar/ziggit.dev/zigo/32/2414_2.png) [@zigo](https://ziggit.dev/u/zigo)\
**Post date:** [July 27, 2023, 9:24am UTC](https://ziggit.dev/t/is-there-a-way-call-a-method-shared-by-all-union-field-types/1288/1 "2023-07-27T09:24:28Z")

</div>

Such as

```zig
const std = @import("std");

const T = union {
	X: struct {
	   fn foo(_: @This()) void {}
	},
	Y: struct {
	   fn foo(_: @This()) void {}
	},
};

pub fn main() !void {
   var t: T = undefined;
   t.X = .{};
   t.foo(); // error: no field or member function named 'foo' in 'T'
}

```

---

<div class="post-metadata">

**Author:** ![AndrewCodeDev](https://ziggit.dev/letter_avatar_proxy/v4/letter/a/278dde/32.png) [@AndrewCodeDev](https://ziggit.dev/u/AndrewCodeDev)\
**Post date:** [July 27, 2023, 9:34am UTC](https://ziggit.dev/t/is-there-a-way-call-a-method-shared-by-all-union-field-types/1288/2 "2023-07-27T09:34:01Z")

</div>

Directly, no… but you could maybe do something like this…

```zig
const T = union(enum) {
	X: struct {
	   fn foo(_: @This()) void { std.debug.print("\nfoo X\n", .{}); }
	},
	Y: struct {
	   fn foo(_: @This()) void { std.debug.print("\nfoo Y\n", .{}); }
	},
    pub fn foo(self: @This()) void {
        switch (self) {
            .X => |x| x.foo(),
            .Y => |y| y.foo(),
        }
    }
};

pub fn main() !void {

    const t: T = .{ .X = .{ } };

    t.foo(); // prints "foo X"
}

```

---

<div class="post-metadata">

**Author:** ![biggest\_endian](https://ziggit.dev/letter_avatar_proxy/v4/letter/b/ea5d25/32.png) [@biggest\_endian](https://ziggit.dev/u/biggest_endian)\
**Post date:** [July 27, 2023, 9:34am UTC](https://ziggit.dev/t/is-there-a-way-call-a-method-shared-by-all-union-field-types/1288/3 "2023-07-27T09:34:53Z")

</div>

This can currently be done by using an inline else in a switch statement.

```zig
switch(t) {
    inline else => |q| q.foo(),
}

```

The inline statement effectively tells the compiler to produce the following code.

```zig
switch(t) {
    .X => |x| x.foo(),
    .Y => |y| y.foo(),
}

```

Read more here: [Easy Interfaces with Zig 0.10](https://zig.news/kristoff/easy-interfaces-with-zig-0100-2hc5)
