Importing based on comptime value

I just mis interpreted your code snippet.

1 Like

Maybe all the catch return are returning early. You could try catch @panic() instead to see if it errs

1 Like

Does not panic. Just writes a segmented output in a file

FWIW I would really like to see the function syntax changed to be more like arrow-functions or lambdas (but without capturing):

const myFunc = fn(a: i32, b: i32) i32 {
    return a + b;
};

…which would then allow things like this:

const myFunc = switch(platform) {
    .macOS => fn(a: i32, b: i32) i32 {
        // do macOS things
    },
    .windows => fn(a: i32, b: i32) i32 {
        // do Windows things
    },
};

…would also match the rest of the syntax nicely (like const Bla = struct { ... }), but most importantly it would solve the problem to define local functions (functions inside functions) in a cleaner way (currently that’s possible but needs a wrapping namespace-struct).

4 Likes

Relevant issue:

And Andrew’s reasoning for rejecting the proposal

2 Likes
const platform: enum { macOS, windows } = .macOS;

const myFunc = @field(struct {
    fn macOS(a: i32, b: i32) i32 {
        return a + b;
    }
    fn windows(a: i32, b: i32) i32 {
        return a - b;
    }
}, @tagName(platform));

:slight_smile:

4 Likes

I guess you weren’t 100% serious with this, but I’d still like to call out that @floooh’s versions is a lot more readable. (And it’s also a lot more readable than the “inner struct” version which is quite commonly used.)

I think that as soon as you have multiple methods that depend on the platform, you actually want the namespace, not just the function, as it’s a nice way to bundle functions that work for a specific platform together. Like this

const WindowsFunctions = struct { 
    fn fun1 …
    fn fun2 …
};
const MacOSFunctions = struct { … };

const PlatformSpecificFunctions = switch (platform) {
    .windows => WindowsFunctions,
    .macOS => MacOSFunctions,
};

and then just bite the bullet and type out PlatformSpecificFunctions.whatever any time you need to use one. Could serve as a nice reminder when you’re calling into something platform specific.

4 Likes

You can do something like this:

const std = @import("std");

fn foo(comptime i: usize) type {
    return struct {
        pub const result = .{
            .number = i,
            .something = "Hello",
            .something_else = "World",
        };
    }; 
}

pub fn main() !void {
    std.debug.print("{}\n", .{foo(345).result});
}

EDIT: removed unnecessary function.

1 Like

Thank you. Yes, I was searching for something like this.