deep_copy.go
deep_copy.go - Overview
This file provides a deep copy functionality for the Obj
struct, including handling of DeepCopyable
interfaces and specific object types.
Detailed Documentation
DeepCopyable Interface
type DeepCopyable interface {
DeepCopy() interface{}
}
- Purpose: Defines an interface for types that support deep copying.
- Methods:
DeepCopy() interface{}
: Creates and returns a deep copy of the implementing object.
Obj.DeepCopy()
func (obj *Obj) DeepCopy() *Obj {
newObj := &Obj{
Type: obj.Type,
LastAccessedAt: obj.LastAccessedAt,
}
// Use the DeepCopyable interface to deep copy the value
if copier, ok := obj.Value.(DeepCopyable); ok {
newObj.Value = copier.DeepCopy()
} else {
// Handle types that are not DeepCopyable
sourceType := obj.Type
switch sourceType {
case ObjTypeString:
sourceValue := obj.Value.(string)
newObj.Value = sourceValue
case ObjTypeJSON:
sourceValue := obj.Value
jsonStr, err := sonic.MarshalString(sourceValue)
if err != nil {
return nil
}
var value interface{}
err = sonic.UnmarshalString(jsonStr, &value)
if err != nil {
return nil
}
newObj.Value = value
default:
return nil
}
}
return newObj
}
- Purpose: Creates a deep copy of an
Obj
struct. - Parameters:
obj *Obj
: TheObj
struct to be deep copied.
- Returns:
*Obj
: A pointer to the newObj
struct, which is a deep copy of the original. Returnsnil
if the object type is not supported or if an error occurs during JSON marshaling/unmarshaling.
Logic:
- A new
Obj
is created with the sameType
andLastAccessedAt
as the original. - If the
Value
field of the originalObj
implements theDeepCopyable
interface, itsDeepCopy()
method is called, and the result is assigned to theValue
field of the newObj
. - If the
Value
field does not implement theDeepCopyable
interface, a type switch is performed on theType
field:- If the type is
ObjTypeString
, the string value is directly copied. - If the type is
ObjTypeJSON
, the value is marshaled to a JSON string and then unmarshaled into a new interface{} value usingsonic
library. - If the type is none of the above, the function returns
nil
.
- If the type is
Code Examples
Not applicable, the code itself serves as a good example.