generated from origadmin/.github
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathload.go
80 lines (67 loc) · 2.56 KB
/
load.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) 2024 GodCong. All rights reserved.
// Package dl for Default Loader
package dl
// DefaultLoader is an interface that can be implemented by structs to customize the default
type DefaultLoader interface {
Default() error
}
// DefaultLoaderFunc is a function type that defines a function to load default values into a struct referenced by a pointer.
type DefaultLoaderFunc[T any] func(*T) error
// DefaultOptionLoader is an interface that specifies a method to load default values into a struct with a parameter.
type DefaultOptionLoader[P any] interface {
Default(P) error
}
// DefaultOptionLoaderFunc is a function type that defines a function to load default values into a struct with a parameter.
type DefaultOptionLoaderFunc[T any, P any] func(*T, P) error
// Load initializes members in a struct referenced by a pointer.
// Maps and slices are initialized by `make` and other primitive types are set with default values.
// `ptr` should be a struct pointer
func Load[T any](ptr *T) error {
if ok, err := LoadInterface(ptr, any(nil)); ok {
return err
}
return LoadStruct(ptr)
}
// MustLoad initializes members in a struct referenced by a pointer.
// Maps and slices are initialized by `make` and other primitive types are set with default values.
// `ptr` should be a struct pointer
func MustLoad[T any](ptr *T) {
if err := Load(ptr); err != nil {
panic(err)
}
}
// LoadWithOption initializes members in a struct referenced by a pointer.
// Maps and slices are initialized by `make` and other primitive types are set with default values.
// `ptr` should be a struct pointer
func LoadWithOption[T any, P any](ptr *T, arg P) error {
if ok, err := LoadInterface(ptr, arg); ok {
return err
}
return LoadStruct(ptr)
}
// LoadInterface initializes members in a struct referenced by a pointer.
// Maps and slices are initialized by `make` and other primitive types are set with default values.
// `ptr` should be a struct pointer
func LoadInterface[P any](ptr any, arg P) (bool, error) {
switch p := ptr.(type) {
case DefaultLoader:
return true, p.Default()
case DefaultOptionLoader[P]:
return true, p.Default(arg)
}
return false, nil
}
// LoadStruct initializes members in a struct referenced by a pointer.
// Maps and slices are initialized by `make` and other primitive types are set with default values.
// `ptr` should be a struct pointer
func LoadStruct(ptr any) error {
return setDefaults(ptr)
}
// Pointer creates a pointer to a value.
func Pointer[T any](v T) *T {
return &v
}
// Object creates a value from a pointer.
func Object[T any](v *T) T {
return *v
}