Field value is passed to a custom function by value instead of by reference, contradicting with `README.md`.
your-diary opened this issue · 1 comments
your-diary commented
According to README.md
(emphasis mine):
custom
Calls one of your functions to perform a custom validation. The field reference will be given as a parameter to the function, which should return a Result<(), ValidationError>.
However, as far as I tested:
-
For
String
field, a custom function receives&String
, which is as expected. -
However, for
usize
field, a custom function receivesusize
instead of&usize
, contradicting with the snippet above.
Minimal Working Example
use validator::{Validate, ValidationError};
//compile error (changing `&usize` to `usize` fixes the error)
fn validate_usize(_: &usize) -> Result<(), ValidationError> {
Ok(())
}
//OK (inconsistent with the function above)
fn validate_string(_: &str) -> Result<(), ValidationError> {
Ok(())
}
#[derive(Debug, Validate)]
struct S {
#[validate(custom(function = "validate_usize"))]
i: usize,
#[validate(custom(function = "validate_string"))]
j: String,
}
fn main() {
let s = S {
i: 10,
j: "hello".to_string(),
};
assert!(s.validate().is_ok());
}
Compiling a v0.1.0 (/Users/user/a)
error[E0308]: mismatched types
--> src/main.rs:13:17
|
13 | #[derive(Debug, Validate)]
| ^^^^^^^^ expected `&usize`, found `usize`
14 | struct S {
15 | #[validate(custom(function = "validate_usize"))]
| ---------------- arguments to this function are incorrect
|
note: function defined here
--> src/main.rs:4:4
|
4 | fn validate_usize(_: &usize) -> Result<(), ValidationError> {
| ^^^^^^^^^^^^^^ ---------
= note: this error originates in the derive macro `Validate` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0308`.
error: could not compile `a` (bin "a") due to 1 previous error
Keats commented
The docs should be updated: fields that can be copied cheaply (essentially all numbers) are passed by values, the rest by reference.