跳到主要内容

11.convert

Convert

apimachinery 库 convert.go

核心代码


// Converter knows how to convert one type to another.
type Converter struct {
// Map from the conversion pair to a function which can
// do the conversion.
conversionFuncs ConversionFuncs
generatedConversionFuncs ConversionFuncs

// Set of conversions that should be treated as a no-op
ignoredConversions map[typePair]struct{}
ignoredUntypedConversions map[typePair]struct{}

// nameFunc is called to retrieve the name of a type; this name is used for the
// purpose of deciding whether two types match or not (i.e., will we attempt to
// do a conversion). The default returns the go type name.
nameFunc func(t reflect.Type) string
}

// Convert will translate src to dest if it knows how. Both must be pointers.
// If no conversion func is registered and the default copying mechanism
// doesn't work on this type pair, an error will be returned.
// 'meta' is given to allow you to pass information to conversion functions,
// it is not used by Convert() other than storing it in the scope.
// Not safe for objects with cyclic references!
func (c *Converter) Convert(src, dest interface{}, meta *Meta) error {
pair := typePair{reflect.TypeOf(src), reflect.TypeOf(dest)}
scope := &scope{
converter: c,
meta: meta,
}

// ignore conversions of this type
if _, ok := c.ignoredUntypedConversions[pair]; ok {
return nil
}
if fn, ok := c.conversionFuncs.untyped[pair]; ok {
return fn(src, dest, scope)
}
if fn, ok := c.generatedConversionFuncs.untyped[pair]; ok {
return fn(src, dest, scope)
}

dv, err := EnforcePtr(dest)
if err != nil {
return err
}
sv, err := EnforcePtr(src)
if err != nil {
return err
}
return fmt.Errorf("converting (%s) to (%s): unknown conversion", sv.Type(), dv.Type())
}


注意点

conversionFuncs 优先级比 generatedConversionFuncs 高,在conversionFuncs找到匹配的函数后,不会再在 generatedConversionFuncs 找

RegisterIgnoredConversion:此函数用于注册一个在类型a和类型b之间的"无操作"转换。当请求在这两种类型之间进行转换时,转换将被忽略。这在某些情况下可能有用,例如当两种类型实际上是相同的,或者它们之间的转换不需要进行任何实际操作时。