-
Notifications
You must be signed in to change notification settings - Fork 0
/
type_converter.go
47 lines (41 loc) · 1.3 KB
/
type_converter.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
package conversion
import (
"reflect"
)
// TypeConverter is an interface for converting types of values from one type to another.
type TypeConverter interface {
CanConvert(source, destination reflect.Type) bool
Convert(source, destination reflect.Value, sourceType, destinationType reflect.Type, mapper Mapper) (
reflect.Value,
error,
)
}
type typeConverter[TSource, TDestination any] struct {
f func(source TSource) (TDestination, error)
}
func (tc typeConverter[TSource, TDestination]) CanConvert(source, destination reflect.Type) bool {
var s TSource
var d TDestination
tSource := reflect.TypeOf(s)
tDestination := reflect.TypeOf(d)
canConvert := source == tSource && destination == tDestination
// log.Printf("CanConvert[%s, %s]: %s -> %s: %v", tSource, tDestination, source, destination, canConvert)
return canConvert
}
func (tc typeConverter[TSource, TDestination]) Convert(
source, destination reflect.Value,
sourceType, destinationType reflect.Type,
mapper Mapper,
) (reflect.Value, error) {
s := source.Interface().(TSource)
d, err := tc.f(s)
if err != nil {
return reflect.Value{}, err
}
return reflect.ValueOf(d), nil
}
func NewTypeConverter[TSource, TDestination any](
f func(source TSource) (TDestination, error),
) TypeConverter {
return typeConverter[TSource, TDestination]{f: f}
}