github.com/searKing/golang/go@v1.2.117/encoding/defaults/convert.go (about) 1 // Copyright 2022 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package defaults 6 7 import ( 8 "reflect" 9 10 "github.com/searKing/golang/go/encoding/internal/tag" 11 reflect_ "github.com/searKing/golang/go/reflect" 12 ) 13 14 const TagDefault = "default" 15 16 // Convert wrapper of convertState 17 func Convert(val any, unmarshal func(data []byte, v any) error) error { 18 return tag.Tag(val, func(val reflect.Value, tag reflect.StructTag) error { 19 fn := newTypeConverter(func(val reflect.Value, tag reflect.StructTag) (isUserDefined bool, err error) { 20 isUserDefined = false 21 if !reflect_.IsEmptyValue(val) { 22 return 23 } 24 defaultTag, ok := tag.Lookup(TagDefault) 25 if !ok { 26 return 27 } 28 return isUserDefined, unmarshal([]byte(defaultTag), val.Addr().Interface()) 29 }, val.Type(), true) 30 31 _, err := fn(val, tag) 32 return err 33 }) 34 } 35 36 // Converter is the interface implemented by types that 37 // can set themselves with default value by struct tag `default`. 38 type Converter interface { 39 ConvertDefault(val reflect.Value, tag reflect.StructTag) error 40 } 41 42 var converterType = reflect.TypeOf(new(Converter)).Elem()