-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequired.go
42 lines (33 loc) · 1.01 KB
/
required.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Copyright (c) 2023-2024 Onur Cinar.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// https://github.com/cinar/checker
package v2
import "reflect"
const (
// nameRequired is the name of the required check.
nameRequired = "required"
)
var (
// ErrRequired indicates that a required value was missing.
ErrRequired = NewCheckError("REQUIRED")
)
// Required checks if the given value of type T is its zero value. It
// returns an error if the value is zero.
func Required[T any](value T) (T, error) {
_, err := reflectRequired(reflect.ValueOf(value))
return value, err
}
// reflectRequired checks if the given value is its zero value. It
// returns an error if the value is zero.
func reflectRequired(value reflect.Value) (reflect.Value, error) {
var err error
if value.IsZero() {
err = ErrRequired
}
return value, err
}
// makeRequired returns the required check function.
func makeRequired(_ string) CheckFunc[reflect.Value] {
return reflectRequired
}