Documentation
¶
Overview ¶
Package melting provides an utility to merge structures of different types. Fields of the source structure are assigned to fields of the destination structure, matching fields by name.
Given a field F: if F is present in the source and destination structures, the source value will override the destination value; if F is present in the source structure but not in destination, the field will be ignored; if F is present in the destination structure, but not in the source, the destination will preserve its value. Embedded sub-structures are supported, and the same algorithm is applied for them.
Example ¶
type Source struct {
F1 int
F2 string
}
type Dest struct {
F1 int
F3 float32
F2 string
}
s := Source{F1: 3, F2: "a"}
d := Dest{F1: 4, F2: "b", F3: 3.1}
// Source will override Dest for fields 'F1', 'F2';
// field 'F3' will be ignored.
// Note that fields order does not count.
err := Melt(s, &d)
if err != nil {
log.Fatalf("cannot assign source to dest, error %v", err)
}
fmt.Printf("Source%v\nDest%v\n", s, d)
Output: Source{3 a} Dest{3 3.1 a}
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Melt ¶
func Melt(src, dest interface{}) error
Melt assigns a source value to a destination. If not, melting is applied. The fields of the destination struct will get the value of the source fields, for those they have in common. If those fields have different types, an error will be returned.
func MeltWithFilter ¶
MeltWithFilter is just like Melt, but with a user supplied filter, that allows to ignore certain fields in the melt.
Example ¶
type Source struct {
F1 int
F2 string
}
type Dest struct {
F1 int
F2 string
F3 float32
}
s := Source{F1: 3, F2: "a"}
d := Dest{F1: 4, F2: "b", F3: 3.1}
// Source will override Dest for field 'F1' only;
// field 'F3' will be ignored because Source does not have it,
// while 'F2' will be ignored because of the filter.
//
// nameFilter is a struct that contains a field name.
// Its 'Filter' function returns true only if the given field
// name is different than the stored one.
err := MeltWithFilter(s, &d, &nameFilter{"F2"})
if err != nil {
log.Fatalf("cannot assign source to dest, error %v", err)
}
fmt.Printf("Source%v\nDest%v\n", s, d)
Output: Source{3 a} Dest{3 b 3.1}
Types ¶
type Filterer ¶
type Filterer interface {
// Filter returns true if the given field name have
// to be considered for the melting. The source and destination
// values are also provided.
Filter(srcField, destField reflect.StructField, src, dest reflect.Value) bool
}
Filterer is an interface that can be used to instrument the melting function to ignore certain fields.
