Is there a way in a where clause in Rust to check if a function passed as a parameter takes specified arguments?
-
1I'm not quite sure what you mean. If specifying a parameter must be a function using a where clause, you typically use the FnOnce, Fn or FnMut traits, which requires specifying the function signature. If using function pointers instead, they are not traits and so do not appear in the where clause.frankplow– frankplow2022-10-11 22:21:51 +00:00Commented Oct 11, 2022 at 22:21
-
@frankplow what I mean is that there could be multiple functions which handle the same parameters but could do different things with it. A main function would take one of this function as a parameter but would need to be sure that they take specified type arguments. I think that it could done with trait but I want to be sure of it can be implemented with a where clause.Lefevre Victor– Lefevre Victor2022-10-11 22:25:49 +00:00Commented Oct 11, 2022 at 22:25
-
"handle the same parameters" - by this do you mean have the same signature? The Fn family of traits are all generic over the arguments they take. For example, a function which implements the Fn(int) trait will always take a single int as an argument. doc.rust-lang.org/std/ops/trait.Fn.html#using-a-fn-parameterfrankplow– frankplow2022-10-11 22:31:01 +00:00Commented Oct 11, 2022 at 22:31
-
Please edit your question to clarify what you want. It would help to have a code snippet of non-working code which illustrates what the thing you want would do, even if you don't know what the syntax for it would be.Kevin Reid– Kevin Reid2022-10-11 22:35:33 +00:00Commented Oct 11, 2022 at 22:35
Add a comment
|
1 Answer
If you're defining a function that takes a function argument, that argument has a very specific type associated with it that dictates the arguments. You cannot call that function with something that doesn't match, it just won't compile.
If you're thinking in terms of dynamic languages where the arguments are somewhat subjective, you're assuming you can make a mistake here and call it incorrectly. You can't. It's strictly disallowed.