#function signature requiring methods on past in type

1 messages · Page 1 of 1 (latest)

modest elk
#

is there a way to tell a function that a passed in type requires certain methods to be defined?

slow eagle
#

could do some vallidation with stuff like if (!@hasField(T, "name")) @compileError("Invalid type passed in");

i dont think there is a better way of expressing "any type that matches this criteria"

modest elk
#

from what i see the documentation @hasFiels does not work for fuctions so it would need to be @hasCecl

but that is not really what i want as it only checks if a method with the name is defined and not for the signature of that method

#

well i could just call the methods with comp-time known values i expect and the compile will tell me if the expectation is wrong

slow eagle
#

true, Decl.... and you can check the signature later by doing @typeInfo(T.name).@"fn"

#

i would just assume correct types are passed in, and let the compiler emit the (maybe cryptic) errors when methods don't exist or don't match the expectation, though

modest elk
#

hmm yeah would work
i just wanted to see if there is a more elegant way then passing additional funtions in
as one of my function signatures has become uncomfortably long

slow eagle
#

could do something like Django's Meta class too

const Meta = struct {
    foo: *const fn (u8, usize) !void,
    // ... whatever ...
}

// types passed in must contain one of these, under a particular name
pub fn theFunc(T: type) void {
    if (!@hasDecl(T, "meta") or @TypeOf(T.meta) != Meta) @compileError("Wrong type");
}
#

by having a struct with known fields (names) and those fields having the arg/return info of your function, you will get good error messages by compiler already, without manually doing checking on your function

#

that's not viable for types that are out of user control (eg: imported from another project) though

modest elk
#

the type is under my control
just wanted to prevent having to refactor the function just because i change something little on the type that does not require a logic change in the function