引用处理
Fory Go 支持引用跟踪,可处理循环引用和共享对象。 This is essential for serializing complex data structures like graphs, trees with parent pointers, and linked lists with cycles.
启用引用跟踪
Reference tracking is disabled by default. Enable it when creating a Fory instance:
f := fory.New(fory.WithTrackRef(true))
Important: Global reference tracking must be enabled for any reference tracking to occur. When WithTrackRef(false) (the default), all per-field reference tags are ignored.
引用跟踪工作原理
Without Reference Tracking (Default)
When disabled, each object is serialized independently:
f := fory.New() // TrackRef disabled by default
shared := &Data{Value: 42}
container := &Container{A: shared, B: shared}
data, _ := f.Serialize(container)
// 'shared' is serialized TWICE (no deduplication)
With Reference Tracking
When enabled, objects are tracked by identity:
f := fory.New(fory.WithTrackRef(true))
shared := &Data{Value: 42}
container := &Container{A: shared, B: shared}
data, _ := f.Serialize(container)
// 'shared' is serialized ONCE, second occurrence is a reference
引用标记
Fory uses flags to indicate reference states during serialization:
| Flag | Value | Meaning |
|---|---|---|
NullFlag | -3 | Nil/null value |
RefFlag | -2 | Reference to previously serialized object |
NotNullValueFlag | -1 | Non-null value (data follows) |
RefValueFlag | 0 | Reference value flag |