Skip to main content

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: The Obj struct to be deep copied.
  • Returns:
    • *Obj: A pointer to the new Obj struct, which is a deep copy of the original. Returns nil if the object type is not supported or if an error occurs during JSON marshaling/unmarshaling.

Logic:

  1. A new Obj is created with the same Type and LastAccessedAt as the original.
  2. If the Value field of the original Obj implements the DeepCopyable interface, its DeepCopy() method is called, and the result is assigned to the Value field of the new Obj.
  3. If the Value field does not implement the DeepCopyable interface, a type switch is performed on the Type 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 using sonic library.
    • If the type is none of the above, the function returns nil.

Code Examples

Not applicable, the code itself serves as a good example.

Getting Started Relevance