Documentation
¶
Overview ¶
Package conv provides generic functions for type conversion and value transformation.
This package offers safe and unsafe conversion utilities between compatible types, including byte/string conversions, reference conversions, reflection-based operations, and string manipulation utilities.
Examples ¶
// Convert bytes to string (zero-copy)
bytes := []byte{'h', 'e', 'l', 'l', 'o'}
str := conv.BytesToString[string](bytes)
fmt.Println(str) // Output: hello
// Convert string to readonly bytes
readonlyBytes := conv.StringToReadonlyBytes("hello")
// Note: modifying readonlyBytes will panic
// Convert to snake_case
snake := conv.SnakeString("UserID")
fmt.Println(snake) // "user_id"
// Convert to CamelCase
camel := conv.CamelString("user_id")
fmt.Println(camel) // "UserId"
Package conv provides generic functions for type conversion and value transformation.
This file contains string manipulation utilities including text formatting, case conversion, encoding conversion, and JSON marshaling.
Index ¶
- func BytesToString[STRING ~string](b []byte) STRING
- func DecodeHTMLEntities(str string, radix int) string
- func DecodeUnicodeEscapes(str string, radix int) string
- func Deref[T any](t *T) T
- func DerefImplType(v reflect.Value) reflect.Type
- func DerefInterfaceValue(v reflect.Value) reflect.Value
- func DerefMap[K comparable, V any](a map[K]*V) map[K]V
- func DerefPtrValue(v reflect.Value) reflect.Value
- func DerefSlice[T any](a []*T) []T
- func DerefSliceValue(v reflect.Value) reflect.Value
- func DerefType(t reflect.Type) reflect.Type
- func DerefValue(v reflect.Value) reflect.Value
- func Indent(text, prefix string) string
- func IsCompositionMethod(method reflect.Method) bool
- func IsExportedName(name string) bool
- func IsExportedOrBuiltinType(t reflect.Type) bool
- func NormalizeWhitespace(str string) string
- func QuoteJSONString(str string, escapeHTML bool) []byte
- func Ref[T any](t T) *T
- func RefMap[K comparable, V any](a map[K]V) map[K]*V
- func RefSlice[T any](a []T) []*T
- func RefSliceValue(v reflect.Value, ptrDepth int) reflect.Value
- func RefType(t reflect.Type, ptrDepth int) reflect.Type
- func RefValue(v reflect.Value, ptrDepth int) reflect.Value
- func SafeAssert[T any](v any) T
- func SafeAssertMap[K comparable, V any](a map[K]any) result.Result[map[K]V]
- func SafeAssertSlice[T any](a []any) result.Result[[]T]
- func ToAnyMap[K comparable, V any](a map[K]V) map[K]any
- func ToAnySlice[T any](a []T) []any
- func ToCamelCase(str string) string
- func ToPascalCase(name string) string
- func ToSnakeCase(str string) string
- func TypeName(obj any) string
- func UnsafeAssertMap[K comparable, V any](a map[K]any) map[K]V
- func UnsafeAssertSlice[T any](a []any) []T
- func UnsafeConvert[T any, U any](t T) U
- func Zero[T any]() T
- type ReadonlyBytes
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BytesToString ¶
BytesToString convert []byte type to ~string type.
func DecodeHTMLEntities ¶ added in v1.20.4
DecodeHTMLEntities converts HTML entity codes to UTF-8 characters.
The radix parameter specifies the numeric base (e.g., 10 for decimal, 16 for hexadecimal). Invalid entities are left unchanged.
Example:
str := `{"info":[["color","ᕸᖹ⁐c;eff;⁐"]]}`
result := DecodeHTMLEntities(str, 16)
// result: `{"info":[["color","咖啡色|绿色"]]}`
func DecodeUnicodeEscapes ¶ added in v1.20.4
DecodeUnicodeEscapes converts Unicode escape sequences (\uXXXX) to UTF-8 characters.
The radix parameter specifies the numeric base (e.g., 10 for decimal, 16 for hexadecimal). Invalid escape sequences are left unchanged. If a code point is longer than 4 characters, only the first 4 are processed.
Example:
str := `{"info":[["color","\u5496\u5561\u8272\u7c\u7eff\u8272"]]}`
result := DecodeUnicodeEscapes(str, 16)
// result: `{"info":[["color","咖啡色|绿色"]]}`
func Deref ¶
func Deref[T any](t *T) T
Deref returns the value of the pointer type. NOTE:
If the value is nil, it will return the zero T.
func DerefImplType ¶
DerefImplType returns the underlying type of the value that implements the interface v.
Examples ¶
```go
var iface interface{} = 42
val := reflect.ValueOf(iface)
typ := conv.DerefImplType(val) // returns int type
```
func DerefInterfaceValue ¶
DerefInterfaceValue returns the value of the underlying type that implements the interface v.
Examples ¶
```go
var iface interface{} = 42
val := reflect.ValueOf(iface)
result := conv.DerefInterfaceValue(val) // returns value of 42
```
func DerefMap ¶
func DerefMap[K comparable, V any](a map[K]*V) map[K]V
DerefMap convert map[K]*V to map[K]V. NOTE:
If a value is nil, it will be set to the zero V.
func DerefPtrValue ¶
DerefPtrValue returns the underlying non-pointer type value.
Examples ¶
```go x := 42 val := reflect.ValueOf(&x) result := conv.DerefPtrValue(val) // returns value of 42 ```
func DerefSlice ¶
func DerefSlice[T any](a []*T) []T
DerefSlice convert []*T to []T. NOTE:
If an element is nil, it will be set to the zero T.
func DerefSliceValue ¶
DerefSliceValue convert []*T to []T.
Examples ¶
```go
x, y := 1, 2
ptrSlice := []*int{&x, &y}
val := reflect.ValueOf(ptrSlice)
result := conv.DerefSliceValue(val) // returns []int{1, 2}
```
func DerefType ¶
DerefType dereference, get the underlying non-pointer type.
Examples ¶
```go typ := reflect.TypeOf((*int)(nil)) baseType := conv.DerefType(typ) // returns int type ```
func DerefValue ¶
DerefValue dereference and unpack interface, get the underlying non-pointer and non-interface value.
Examples ¶
```go x := 42 val := reflect.ValueOf(&x) result := conv.DerefValue(val) // returns value of 42 ```
func Indent ¶ added in v1.20.4
Indent inserts the given prefix at the beginning of each line in the text.
If prefix is empty, the original text is returned unchanged. If text is empty, returns empty string. Empty lines (lines containing only newline) are not indented. The function preserves the trailing newline if present in the input.
Example:
result := Indent("line1\n\nline2", " ")
// result: " line1\n\n line2"
func IsCompositionMethod ¶ added in v1.20.3
IsCompositionMethod determines whether the method is inherited from an anonymous field (composition). It checks if the method is auto-generated by Go's composition mechanism.
NOTE: This function relies on the "<autogenerated>" file marker used by Go's compiler for composition methods. This may not be reliable in all cases.
Examples ¶
```go
type Base struct{}
func (Base) Method() {}
type Derived struct {
Base // anonymous field
}
method, _ := reflect.TypeOf(Derived{}).MethodByName("Method")
if conv.IsCompositionMethod(method) {
// Method is inherited from Base
}
```
func IsExportedName ¶ added in v1.20.3
IsExportedName checks if the name is exported (starts with uppercase letter).
Examples ¶
```go
if conv.IsExportedName("MyFunction") {
// Name is exported
}
```
func IsExportedOrBuiltinType ¶ added in v1.20.3
IsExportedOrBuiltinType checks if the type is exported or a builtin type. It dereferences pointer types before checking.
Examples ¶
```go
typ := reflect.TypeOf(MyStruct{})
if conv.IsExportedOrBuiltinType(typ) {
// Type is exported or builtin
}
```
func NormalizeWhitespace ¶ added in v1.20.4
NormalizeWhitespace combines multiple consecutive whitespace characters into normalized form.
Rules (industry standard):
- Multiple spaces -> single space
- Multiple tabs -> single tab
- 3+ newlines -> 2 newlines (paragraph separator)
- 2 newlines after space/tab -> 1 newline (whitespace block normalization)
- 2 newlines between content -> preserved (paragraph break)
- Trailing spaces/tabs before newlines -> removed
Example:
input := "hello world\n\n\ttest" result := NormalizeWhitespace(input) // result: "hello world\n\ttest"
func QuoteJSONString ¶ added in v1.20.4
QuoteJSONString converts a string to a JSON-encoded byte array.
The escapeHTML parameter controls whether HTML characters (<, >, &) are escaped. When true, these characters are escaped to prevent security issues when embedding JSON in HTML <script> tags.
Example:
str := `<>&{}""`
json1 := QuoteJSONString(str, true)
// json1: "\u003c\u003e\u0026{}\"\""
json2 := QuoteJSONString(str, false)
// json2: "<>&{}\"\""
Example ¶
str := `<>&{}""`
fmt.Printf("%s\n", QuoteJSONString(str, true))
fmt.Printf("%s\n", QuoteJSONString(str, false))
Output: "\u003c\u003e\u0026{}\"\"" "<>&{}\"\""
func RefMap ¶
func RefMap[K comparable, V any](a map[K]V) map[K]*V
RefMap convert map[K]V to map[K]*V.
func RefSliceValue ¶
RefSliceValue convert []T to []*T, the ptrDepth is the count of '*'.
Examples ¶
```go
slice := []int{1, 2}
val := reflect.ValueOf(slice)
result := conv.RefSliceValue(val, 1) // returns []*int{&1, &2}
```
func RefType ¶
RefType convert T to *T, the ptrDepth is the count of '*'.
Examples ¶
```go typ := reflect.TypeOf(42) ptrType := conv.RefType(typ, 1) // returns *int type ```
func RefValue ¶
RefValue convert T to *T, the ptrDepth is the count of '*'.
Examples ¶
```go val := reflect.ValueOf(42) ptrVal := conv.RefValue(val, 1) // returns *int pointing to 42 ```
func SafeAssertMap ¶
func SafeAssertMap[K comparable, V any](a map[K]any) result.Result[map[K]V]
SafeAssertMap convert map[K]any to map[K]V.
func SafeAssertSlice ¶
SafeAssertSlice convert []any to []T.
func ToAnyMap ¶
func ToAnyMap[K comparable, V any](a map[K]V) map[K]any
ToAnyMap convert map[K]V to map[K]any.
func ToCamelCase ¶ added in v1.20.4
ToCamelCase converts a string to CamelCase format.
Examples:
- "xx_yy" -> "XxYy"
- "user_id" -> "UserId"
- "tcp_rpc" -> "TcpRpc"
- "user_id_123" -> "UserId123" (underscores before numbers are removed)
- "a__b__c" -> "A__B__C" (multiple underscores are preserved)
func ToPascalCase ¶ added in v1.20.4
ToPascalCase converts a string to PascalCase format with support for common initialisms.
Common initialisms like "ID", "RPC", "TCP" are preserved in uppercase.
Examples:
- "xx_yy" -> "XxYy"
- "user_id" -> "UserID"
- "tcp_rpc" -> "TCPRPC"
- "wake_rpc" -> "WakeRPC"
func ToSnakeCase ¶ added in v1.20.4
ToSnakeCase converts a string to snake_case format.
Examples:
- "XxYy" -> "xx_yy"
- "UserID" -> "user_id"
- "TCP_RPC" -> "tcp_rpc"
func TypeName ¶ added in v1.20.3
TypeName gets the type name of the object. For functions, it returns the function name from runtime. For other types, it returns the type string representation.
Examples ¶
```go
name := conv.TypeName(42) // "int"
name := conv.TypeName(&MyStruct{}) // "*conv.MyStruct"
```
func UnsafeAssertMap ¶
func UnsafeAssertMap[K comparable, V any](a map[K]any) map[K]V
UnsafeAssertMap convert map[K]any to map[K]V.
func UnsafeAssertSlice ¶
UnsafeAssertSlice convert []any to []T.
func UnsafeConvert ¶
UnsafeConvert convert a value to another type.
Types ¶
type ReadonlyBytes ¶
type ReadonlyBytes = []byte
func StringToReadonlyBytes ¶
func StringToReadonlyBytes[STRING ~string](s STRING) ReadonlyBytes
StringToReadonlyBytes convert ~string to unsafe read-only []byte. NOTE:
panic if modify the member value of the ReadonlyBytes.