feat: 支持切片追加及 -1 头部插入
This commit is contained in:
42
README.md
42
README.md
@@ -246,6 +246,46 @@ rfx.Set("NewMap.key", "value") // 如果 NewMap 是 nil,会自动初始化
|
||||
|
||||
**注意**: 如果设置失败(路径不存在、类型不匹配等),会 panic。
|
||||
|
||||
#### 切片追加 (Append)
|
||||
|
||||
`Append` 用于在当前 `R` 对应的切片上追加一个或多个元素,并支持自动类型转换:
|
||||
|
||||
```go
|
||||
// 追加到顶层切片
|
||||
items := []string{"apple", "banana"}
|
||||
rfx := reflux.New(&items)
|
||||
|
||||
// 追加单个和多个元素
|
||||
rfx.Append("cherry")
|
||||
rfx.Append("durian", "kiwi")
|
||||
// items == []string{"apple", "banana", "cherry", "durian", "kiwi"}
|
||||
|
||||
// 使用索引 -1 在切片前面插入新元素
|
||||
// 相当于在开头插入,原有元素整体后移
|
||||
rfx.Set("-1", "first")
|
||||
// 对于上面的 items,现在结果为:
|
||||
// items == []string{"first", "apple", "banana", "cherry", "durian", "kiwi"}
|
||||
|
||||
// 追加时支持类型转换
|
||||
nums := []int{1, 2}
|
||||
rfxNums := reflux.New(&nums)
|
||||
rfxNums.Append("3", 4.0) // "3" -> 3, 4.0 -> 4
|
||||
// nums == []int{1, 2, 3, 4}
|
||||
|
||||
// 追加到嵌套切片字段
|
||||
type Container struct {
|
||||
Tags []string
|
||||
}
|
||||
c := Container{Tags: []string{"go"}}
|
||||
rfxContainer := reflux.New(&c)
|
||||
rfxContainer.Get("Tags").Append("rust", "python")
|
||||
// c.Tags == []string{"go", "rust", "python"}
|
||||
```
|
||||
|
||||
**注意**:
|
||||
- 只能对**切片类型**调用 `Append`,否则会 panic
|
||||
- 追加多个值时会一次性追加,避免多次扩容
|
||||
|
||||
### 5. 删除值 (Delete)
|
||||
|
||||
`Delete` 方法支持链式调用,返回 Reflux 自身:
|
||||
@@ -774,4 +814,4 @@ type Reflux interface {
|
||||
8. **大小写不敏感**: 支持使用小写字段名访问结构体字段
|
||||
9. **JSON 集成**: Ptr() 返回的指针可以安全地用于 json.Unmarshal()
|
||||
10. **并发安全**: Reflux 本身不是并发安全的,需要外部同步
|
||||
11. **错误处理**: 大多数转换、设置和删除操作失败时会 panic,请确保路径和类型正确
|
||||
11. **错误处理**: 大多数转换、设置和删除操作失败时会 panic,请确保路径和类型正确
|
||||
|
||||
Reference in New Issue
Block a user