fix: New()/Array() 正确处理 Nil 及已经是 R 的元素,不再 panic/重复包装
New(nil) 之前会 panic,现在返回 Nil(新增的 R 空实现单例,所有操作都是
安全的空操作/零值,不用调用方每次都判空)。New([]R{...}) 和 Array() 遇到
元素本身已经是 R(包括 Nil)时直接透传,不再重新拿 reflect.Value 包一层,
避免丢失原有的空值语义或类型信息。
This commit is contained in:
@@ -4,6 +4,39 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestNewWithNilR 测试 New 接收包含 Nil 的 []R
|
||||
func TestNewWithNilR(t *testing.T) {
|
||||
t.Run("New with []R{Nil}", func(t *testing.T) {
|
||||
r := New([]R{Nil})
|
||||
arr := r.Array()
|
||||
if len(arr) != 1 {
|
||||
t.Fatalf("Expected Array() len 1, got %d", len(arr))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Array element from []R{Nil} behaves as Nil", func(t *testing.T) {
|
||||
r := New([]R{Nil})
|
||||
elem := r.Array()[0]
|
||||
if elem.Exists() {
|
||||
t.Error("Expected Exists() to be false for Nil element")
|
||||
}
|
||||
if elem.Any() != nil {
|
||||
t.Errorf("Expected Any() to be nil, got %v", elem.Any())
|
||||
}
|
||||
if elem.String() != "" {
|
||||
t.Errorf("Expected String() to be empty, got %q", elem.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("New with []R{Nil} Slice()", func(t *testing.T) {
|
||||
r := New([]R{Nil})
|
||||
s := r.Slice()
|
||||
if len(s) != 1 {
|
||||
t.Fatalf("Expected Slice() len 1, got %d", len(s))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestSetValueWithNil 测试 setValue 方法处理 nil 值的各种情况
|
||||
func TestSetValueWithNil(t *testing.T) {
|
||||
t.Run("Set nil to pointer field", func(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user