olekukonko/cat
GitHub: olekukonko/cat
`cat` 是一个 Go 语言的高性能流式字符串拼接库,通过链式 API、自动类型转换和对象池化等机制,让复杂字符串构建更快更简洁。
Stars: 1 | Forks: 0
# 🐱 `cat` - 适用于 Go 的快速且流式的字符串拼接库
## 为什么选择 `cat`?
Go 的 `strings.Builder` 很好用,但构建复杂的字符串通常显得笨拙。`cat` 让字符串拼接变得:
- **更快** - 针对常见类型优化执行路径,实现零分配转换
- **更流式** - 可链式调用的方法,造就优雅、易读的代码
- **更灵活** - 处理任何类型、嵌套结构和自定义格式
- **更智能** - 自动池化、大小预估和分隔符处理
```
// Without cat
var b strings.Builder
b.WriteString("Hello, ")
b.WriteString(user.Name)
b.WriteString("! You have ")
b.WriteString(strconv.Itoa(count))
b.WriteString(" new messages.")
result := b.String()
// With cat
result := cat.Concat("Hello, ", user.Name, "! You have ", count, " new messages.")
```
## 🔥 核心特性
### 1. 流式 Builder API
通过方法链式调用,霸气地构建字符串:
```
s := cat.New(", ").
Add("apple").
If(user.IsVIP, "golden kiwi").
Add("orange").
Sep(" | "). // Change separator mid-way
Add("banana").
String()
// "apple, golden kiwi, orange | banana"
```
### 2. 零分配的魔法
- **池化 Builder**(可选)减轻 GC 压力
- **不安全的字节转换**(可选择开启)避免 `[]byte`→`string` 的复制
- 为数字使用**栈缓冲区**,替代堆分配
```
// Enable performance features
cat.Pool(true) // Builder pooling
cat.SetUnsafeBytes(true) // Zero-copy []byte conversion
```
### 3. 处理任何类型 - 甚至是嵌套类型!
告别手动类型转换:
```
data := map[string]any{
"id": 12345,
"tags": []string{"go", "fast", "efficient"},
}
fmt.Println(cat.JSONPretty(data))
// {
// "id": 12345,
// "tags": ["go", "fast", "efficient"]
// }
```
### 4. 满足各种用例的拼接
```
// Simple joins
cat.With(", ", "apple", "banana", "cherry") // "apple, banana, cherry"
// File paths
cat.Path("dir", "sub", "file.txt") // "dir/sub/file.txt"
// CSV
cat.CSV(1, 2, 3) // "1,2,3"
// Conditional elements
cat.Start("Hello").If(user != nil, " ", user.Name) // "Hello" or "Hello Alice"
// Repeated patterns
cat.RepeatWith("-+", "X", 3) // "X-+X-+X"
```
### 5. 比普通的字符串库更智能
```
// Automatic nesting handling
nested := []any{"a", []any{"b", "c"}, "d"}
cat.FlattenWith(",", nested) // "a,b,c,d"
// Precise size estimation (minimizes allocations)
b := cat.New(", ").Grow(estimatedSize) // Preallocate exactly what you need
// Reflection support for any type
cat.Reflect(anyComplexStruct) // "{Field1:value Field2:[1 2 3]}"
```
## 🚀 快速入门
```
go get github.com/your-repo/cat
```
```
import "github.com/your-repo/cat"
func main() {
// Simple concatenation
msg := cat.Concat("User ", userID, " has ", count, " items")
// Pooled builder (for high-performance loops)
builder := cat.New(", ")
defer builder.Release() // Return to pool
result := builder.Add(items...).String()
}
```
## 🤔 为什么不直接用...?
- `fmt.Sprintf` - 速度慢,产生大量分配
- `strings.Join` - 仅适用于字符串
- `bytes.Buffer` - 无内置分隔符支持,需手动处理类型
- `string +` - 性能更差,尤其是在循环中
## 💡 专家提示
1. 在高吞吐量场景下**开启池化**
2. 当你知道最终大小时,使用 `.Grow()` **预分配**
3. 在流式链路中使用 **`If()`** 处理条件元素
4. 如果你能保证字节切片不会被修改,请尝试 **`SetUnsafeBytes(true)`**
5. 当开启池化时,请务必**释放 Builder**
## 🐱👤 高级用法
```
// Custom value formatting
type User struct {
Name string
Age int
}
func (u User) String() string {
return cat.With(" ", u.Name, cat.Wrap("(", u.Age, ")"))
}
// JSON-like output
func JSONPretty(v any) string {
return cat.WrapWith(",\n ", "{\n ", "\n}", prettyFields(v))
}
```
```
/\_/\
( o.o ) > Concatenate with purr-fection!
> ^ <
```
**`cat`** - 因为生命短暂,不应浪费在编写丑陋的字符串构建代码上。😻
标签:EVTX分析, Go, Ruby工具, 内存优化, 字符串处理, 开发工具库, 日志审计, 链式调用