#How could I return a generic struct of a non specified type?

1 messages · Page 1 of 1 (latest)

dapper nest
#

given this struct:

pub fn GenericType(comptime T: type) type {
    return struct {
        field1: T,

        pub fn init(field1: T) @This() {
            return .{ .field1 = field1 };
        }
    };
}

how could i return this struct in a function, without the type specified, for instance:

pub fn doAThing(...) GenericType {
  ...
}
dull nimbus
#

Here GenericType is a name of a function, so you can't return it as a type/struct.

#

But GenericType(<type>) is a type, so you could do
pub fn doAthing(...) GenericType(<type>) {...}

shut scarab
#

If the desired behavior of not specifying the type is for it to be inferred, instead you could do something like

fn DetermineType(...args) type {
    // determine what type doAThing will return based on some logic
}
pub fn doAthing(...args) GenericType(DetermineType(...args)) {...}
#

DetermineType will only be able to look at comptime args though

dull nimbus
#

Yes that's possible.

shut scarab
#

You can't in general have a type be known only at runtime

dull nimbus
#

Yes since types only exist in comptime and can only depend on comptime knowns.

dapper nest
#

hmm

#

this is a bit of a problem i guess

#

because i cannot specify the type at compile time

#

what could be a solution

fringe iron
#

Return an union

#

That can contain all the possible return types you want

dapper nest
#

the problem is that it should be able to be any possible type

#

is there anyway that i could have a value be any type at run time?

shut scarab
#

Not in a way that lets you remember the type

#

Depending on the use-case, it might still be possible to do what you're doing, but there are infinite types and code cannot be infinitely big

#

Like for generic functions, Zig creates a different function for each type argument so that there is no type information at runtime. In order for this to be possible, the set of type inputs that function is called with must be known at compile time

#

You can't have generic functions that are instantiated for every possible type

dapper nest
#

so there is no void * equivalent for zig?

shut scarab
#

There is, but that loses type information

#

In Zig it is *anyopaque

fringe iron
#

that's how void * works

dapper nest
#

okay cool

#

am i able to cast that type to any type with like @as

fringe iron
#

not with as

dapper nest
#

@ptrCast?

#

idfk

fringe iron
#

const typed: *NewType = @ptrCast(@alignCast(opaque));

dapper nest
#

okay cool

#

thanks

#

what does alignCast do?

fringe iron
#

casts from a type with one alignment to another

dapper nest
#

okay got it

fringe iron
#

*anyopaque looses both type and alignment information

#

need to bring back both