Documentation
¶
Overview ¶
Example (StringPointerBasic) ¶
Estos ejemplos ilustran cómo usar los punteros a strings para evitar asignaciones adicionales
// Creamos una variable string que queremos modificar myText := "héllô wórld" // En lugar de crear una nueva variable con el resultado, // modificamos directamente la variable original usando Apply() Convert(&myText).Tilde().Low().Apply() // La variable original ha sido modificada fmt.Println(myText)
Output: hello world
Example (StringPointerCamelCase) ¶
// Ejemplo de uso con múltiples transformaciones originalText := "Él Múrcielago Rápido" // Las transformaciones modifican la variable original directamente // usando el método Apply() para actualizar el puntero Convert(&originalText).Tilde().CamelLow().Apply() fmt.Println(originalText)
Output: elMurcielagoRapido
Example (StringPointerEfficiency) ¶
// En aplicaciones de alto rendimiento, reducir asignaciones de memoria // puede ser importante para evitar la presión sobre el garbage collector // Método tradicional (crea nuevas asignaciones de memoria) traditionalText := "Texto con ACENTOS" processedText := Convert(traditionalText).Tilde().Low().String() fmt.Println(processedText) // Método con punteros (modifica directamente la variable original) directText := "Otro TEXTO con ACENTOS" Convert(&directText).Tilde().Low().Apply() fmt.Println(directText)
Output: texto con acentos otro texto con acentos
Index ¶
- Constants
- Variables
- func Contains(conv, search string) bool
- func Convert(v ...any) *conv
- func Count(conv, search string) int
- func Err(msgs ...any) *conv
- func Errf(format string, args ...any) *conv
- func Fmt(format string, args ...any) string
- func OutLang(l ...any)
- func T(values ...any) string
- type Kind
- type LocStr
Examples ¶
Constants ¶
const ( // Group 1: Core Essential Languages (Maximum Global Reach) EN lang = iota // 0 - English (default) ES // 1 - Spanish ZH // 2 - Chinese HI // 3 - Hindi AR // 4 - Arabic // Group 2: Extended Reach Languages (Europe & Americas) PT // 5 - Portuguese FR // 6 - French DE // 7 - German RU // 8 - Russian )
Variables ¶
var D = struct { Allowed LocStr // "allowed" Changed LocStr // "changed" Argument LocStr // "argument" Assign LocStr // "assign" Assignable LocStr // "assignable" BackingUp LocStr // "backing up" Be LocStr // "be" Binary LocStr // "binary" Call LocStr // "call" Cannot LocStr // "cannot" Cancel LocStr // "cancel" Character LocStr // "character" Coding LocStr // "coding" Compilation LocStr // "compilation" Configuration LocStr // "configuration" Connection LocStr // "connection" Debugging LocStr // "debugging" Decimal LocStr // "decimal" Delimiter LocStr // "delimiter" Digit LocStr // "digit" Element LocStr // "element" Empty LocStr // "empty" End LocStr // "end" Exceeds LocStr // "exceeds" Execute LocStr // "execute" Failed LocStr // "failed" Field LocStr // "field" Fields LocStr // "fields" Files LocStr // "files" Format LocStr // "format" Found LocStr // "found" Handler LocStr // "handler" Language LocStr // "language" Icons LocStr // "icons" Implemented LocStr // "implemented" In LocStr // "in" Index LocStr // "index" Information LocStr // "information" Input LocStr // "input" Install LocStr // "install" Installation LocStr // "installation" Invalid LocStr // "invalid" Maximum LocStr // "maximum" Method LocStr // "method" Missing LocStr // "missing" Mismatch LocStr // "mismatch" Mode LocStr // "mode" Modes LocStr // "modes" More LocStr // "more" Move LocStr // "move" Must LocStr // "must" Negative LocStr // "negative" Nil LocStr // "null" NonNumeric LocStr // "non-numeric" Not LocStr // "not" NotOfType LocStr // "not of type" Number LocStr // "number" Numbers LocStr // "numbers" Of LocStr // "of" Options LocStr // "options" Out LocStr // "out" Overflow LocStr // "overflow" Page LocStr // "page" Pointer LocStr // "pointer" Point LocStr // "point" Preparing LocStr // "preparing" Production LocStr // "production" Provided LocStr // "provided" Quit LocStr // "quit" Range LocStr // "range" Read LocStr // "read" Required LocStr // "required" Round LocStr // "round" Seconds LocStr // "seconds" Session LocStr // "session" Slice LocStr // "slice" Space LocStr // "space" Status LocStr // "status" String LocStr // "string" Supported LocStr // "supported" Switch LocStr // "switch" Switching LocStr // "switching" Sync LocStr // "sync" System LocStr // "system" Test LocStr // "test" Testing LocStr // "testing" Time LocStr // "time" To LocStr // "to" Type LocStr // "type" Unexported LocStr // "unexported" Unknown LocStr // "unknown" Unsigned LocStr // "unsigned" Use LocStr // "use" Valid LocStr // "valid" Validating LocStr // "validating" Value LocStr // "value" Zero LocStr // "zero" }{ LocStr{"allowed", "permitido", "允许", "अनुमति", "مسموح", "permitido", "autorisé", "erlaubt", "разрешено"}, LocStr{"changed", "cambiado", "更改", "परिवर्तित", "تم التغيير", "alterado", "changé", "geändert", "изменено"}, LocStr{"argument", "argumento", "参数", "तर्क", "وسيط", "argumento", "argument", "Argument", "аргумент"}, LocStr{"assign", "asignar", "分配", "असाइन", "تعيين", "atribuir", "assigner", "zuweisen", "присвоить"}, LocStr{"assignable", "asignable", "可分配", "असाइन करने योग्य", "قابل للتعيين", "atributável", "assignable", "zuweisbar", "присваиваемый"}, LocStr{"backing up", "respaldando", "备份", "बैकअप", "نسخ احتياطي", "fazendo backup", "sauvegarde", "Sicherung", "резервное копирование"}, LocStr{"be", "ser", "是", "होना", "كون", "ser", "être", "sein", "быть"}, LocStr{"binary", "binario", "二进制", "二进制", "ثنائي", "binário", "binaire", "binär", "двоичный"}, LocStr{"call", "llamar", "调用", "कॉल", "استدعاء", "chamar", "appeler", "aufrufen", "вызвать"}, LocStr{"cannot", "no puede", "不能", "नहीं कर सकते", "لا يمكن", "não pode", "ne peut pas", "kann nicht", "не может"}, LocStr{"cancel", "cancelar", "取消", "रद्द करें", "إلغاء", "cancelar", "annuler", "abbrechen", "отменить"}, LocStr{"character", "caracter", "字符", "वर्ण", "حرف", "caractere", "caractère", "Zeichen", "символ"}, LocStr{"coding", "codificación", "编码", "कोडिंग", "ترميز", "codificação", "codage", "kodierung", "кодирование"}, LocStr{"compilation", "compilación", "编译", "संकलन", "تجميع", "compilação", "compilation", "kompilierung", "компиляция"}, LocStr{"configuration", "configuración", "配置", "कॉन्फ़िगरेशन", "تكوين", "configuração", "configuration", "Konfiguration", "конфигурация"}, LocStr{"connection", "conexión", "连接", "संपर्क", "اتصال", "conexão", "connexion", "Verbindung", "соединение"}, LocStr{"debugging", "depuración", "调试", "डिबगिंग", "تصحيح", "depuração", "débogage", "debuggen", "отладка"}, LocStr{"decimal", "decimal", "十进制", "दशमलव", "عشري", "decimal", "décimal", "Dezimal", "десятичная"}, LocStr{"delimiter", "delimitador", "分隔符", "सीमांकक", "محدد", "delimitador", "délimiteur", "Trennzeichen", "разделитель"}, LocStr{"digit", "dígito", "数字", "अंक", "رقم", "dígito", "chiffre", "Ziffer", "цифра"}, LocStr{"element", "elemento", "元素", "एलिमेंट", "عنصر", "elemento", "élément", "Element", "элемент"}, LocStr{"empty", "vacío", "空", "खाली", "فارغ", "vazio", "vide", "leer", "пустой"}, LocStr{"end", "fin", "结束", "अंत", "نهاية", "fim", "fin", "Ende", "конец"}, LocStr{"exceeds", "excede", "超过", "अधिक", "يتجاوز", "excede", "dépasse", "überschreitet", "превышает"}, LocStr{"execute", "ejecutar", "执行", "निष्पादित करें", "تنفيذ", "executar", "exécuter", "ausführen", "выполнить"}, LocStr{"failed", "falló", "失败", "असफल", "فشل", "falhou", "échoué", "fehlgeschlagen", "не удалось"}, LocStr{"field", "campo", "字段", "फील्ड", "حقل", "campo", "champ", "Feld", "поле"}, LocStr{"fields", "campos", "字段集", "फील्ड्स", "حقول", "campos", "champs", "Felder", "поля"}, LocStr{"files", "archivos", "文件", "फ़ाइलें", "ملفات", "arquivos", "fichiers", "Dateien", "файлы"}, LocStr{"format", "formato", "格式", "प्रारूप", "تنسيق", "formato", "format", "Fmt", "формат"}, LocStr{"found", "encontrado", "找到", "मिला", "موجود", "encontrado", "trouvé", "gefunden", "найден"}, LocStr{"handler", "manejador", "处理程序", "हैंडलर", "معالج", "manipulador", "gestionnaire", "Handler", "обработчик"}, LocStr{"language", "idioma", "语言", "भाषा", "لغة", "idioma", "langue", "Sprache", "язык"}, LocStr{"icons", "iconos", "图标", "आइकन", "أيقونات", "ícones", "icônes", "Symbole", "значки"}, LocStr{"implemented", "implementado", "已实现", "कार्यान्वित", "مُنفذ", "implementado", "implémenté", "implementiert", "реализовано"}, LocStr{"in", "en", "在", "में", "في", "em", "dans", "in", "в"}, LocStr{"index", "índice", "索引", "इंडेक्स", "فهرس", "índice", "index", "Index", "индекс"}, LocStr{"information", "información", "信息", "सूचना", "معلومات", "informação", "information", "Information", "информация"}, LocStr{"input", "entrada", "输入", "इनपुट", "إدخال", "entrada", "entrée", "eingabe", "ввод"}, LocStr{"install", "instalar", "安装", "इंस्टॉल", "تثبيت", "instalar", "installer", "installieren", "установить"}, LocStr{"installation", "instalación", "安装", "स्थापना", "التثبيت", "instalação", "installation", "installation", "установка"}, LocStr{"invalid", "inválido", "无效", "अमान्य", "غير صالح", "inválido", "invalide", "ungültig", "недопустимый"}, LocStr{"maximum", "máximo", "最大", "अधिकतम", "الحد الأقصى", "máximo", "maximum", "Maximum", "максимум"}, LocStr{"method", "método", "方法", "विधि", "طريقة", "método", "méthode", "Methode", "метод"}, LocStr{"missing", "falta", "缺少", "गुम", "مفقود", "ausente", "manquant", "fehlend", "отсутствует"}, LocStr{"mismatch", "desajuste", "不匹配", "बेमेल", "عدم تطابق", "incompatibilidade", "incompatibilité", "Nichtübereinstimmung", "несоответствие"}, LocStr{"mode", "modo", "模式", "मोड", "وضع", "modo", "mode", "Modus", "режим"}, LocStr{"modes", "modos", "模式", "मोड", "أوضاع", "modos", "modes", "Modi", "режимы"}, LocStr{"more", "más", "更多", "अधिक", "أكثر", "mais", "plus", "mehr", "больше"}, LocStr{"must", "debe", "必须", "चाहिए", "يجب", "deve", "doit", "muss", "должен"}, LocStr{"move", "mover", "移动", "स्थानांतरित करें", "نقل", "mover", "déplacer", "verschieben", "переместить"}, LocStr{"negative", "negativo", "负", "नकारात्मक", "سالب", "negativo", "négatif", "negativ", "отрицательный"}, LocStr{"nil", "nulo", "空值", "शून्य मान", "قيمة فارغة", "nulo", "nul", "Nullwert", "нуль"}, LocStr{"non-numeric", "no numérico", "非数字", "गैर-संख्यात्मक", "غير رقمي", "não numérico", "non numérique", "nicht numerisch", "нечисловой"}, LocStr{"not", "no", "不", "नहीं", "ليس", "não", "pas", "nicht", "не"}, LocStr{"not of type", "no es del tipo", "不是类型", "प्रकार नहीं है", "ليس من النوع", "não é do tipo", "n'est pas du type", "ist nicht vom Typ", "не того типа"}, LocStr{"number", "número", "数字", "संख्या", "رقم", "número", "nombre", "Zahl", "число"}, LocStr{"numbers", "números", "数字", "संख्याएं", "أرقام", "números", "nombres", "Zahlen", "числа"}, LocStr{"of", "de", "的", "का", "من", "de", "de", "von", "из"}, LocStr{"options", "opciones", "选项", "विकल्प", "خيارات", "opções", "options", "Optionen", "опции"}, LocStr{"out", "fuera", "出", "बाहर", "خارج", "fora", "hors", "aus", "вне"}, LocStr{"overflow", "desbordamiento", "溢出", "ओवरफ्लो", "فيض", "estouro", "débordement", "Überlauf", "переполнение"}, LocStr{"page", "página", "页面", "पृष्ठ", "صفحة", "página", "page", "Seite", "страница"}, LocStr{"pointer", "puntero", "指针", "पॉइंटर", "مؤشر", "ponteiro", "pointeur", "Zeiger", "указатель"}, LocStr{"point", "punto", "点", "बिंदु", "نقطة", "ponto", "point", "Punkt", "точка"}, LocStr{"preparing", "preparando", "准备", "तैयारी", "تحضير", "preparando", "préparation", "Vorbereitung", "подготовка"}, LocStr{"production", "producción", "生产", "उत्पादन", "إنتاج", "produção", "production", "produktion", "производство"}, LocStr{"provided", "proporcionado", "提供", "प्रदान किया गया", "مقدم", "fornecido", "fourni", "bereitgestellt", "предоставлено"}, LocStr{"quit", "salir", "退出", "छोड़ें", "إنهاء", "sair", "quitter", "beenden", "выйти"}, LocStr{"range", "rango", "范围", "रेंज", "نطاق", "intervalo", "plage", "Bereich", "диапазон"}, LocStr{"read", "leer", "读取", "पढ़ें", "قراءة", "ler", "lire", "lesen", "читать"}, LocStr{"required", "requerido", "必需", "आवश्यक", "مطلوب", "necessário", "requis", "erforderlich", "обязательный"}, LocStr{"round", "redondear", "圆", "गोल", "جولة", "arredondar", "arrondir", "runden", "округлить"}, LocStr{"seconds", "segundos", "秒", "सेकंड", "ثواني", "segundos", "secondes", "Sekunden", "секунды"}, LocStr{"session", "sesión", "会话", "सत्र", "جلسة", "sessão", "session", "Sitzung", "сессия"}, LocStr{"slice", "segmento", "切片", "स्लाइस", "شريحة", "fatia", "tranche", "Scheibe", "срез"}, LocStr{"space", "espacio", "空间", "जगह", "فضاء", "espaço", "espace", "Raum", "пространство"}, LocStr{"status", "estado", "状态", "स्थिति", "حالة", "status", "statut", "Status", "статус"}, LocStr{"string", "cadena", "字符串", "स्ट्रिंग", "سلسلة", "string", "chaîne", "Zeichenkette", "строка"}, LocStr{"supported", "soportado", "支持", "समर्थित", "مدعوم", "suportado", "pris en charge", "unterstützt", "поддерживается"}, LocStr{"switch", "cambiar", "切换", "स्विच", "تبديل", "mudar", "changer", "wechseln", "переключить"}, LocStr{"switching", "cambiando", "切换中", "स्विच कर रहा है", "تبديل", "mudando", "changement", "wechseln", "переключение"}, LocStr{"sync", "sincronización", "同步", "सिंक", "مزامنة", "sincronização", "synchronisation", "Synchronisierung", "синхронизация"}, LocStr{"system", "sistema", "系统", "सिस्टम", "نظام", "sistema", "système", "System", "система"}, LocStr{"test", "prueba", "测试", "परीक्षण", "اختبار", "teste", "test", "Test", "тест"}, LocStr{"testing", "probando", "测试中", "परीक्षण", "اختبارات", "testando", "test", "testen", "тестирование"}, LocStr{"time", "tiempo", "时间", "समय", "وقت", "tempo", "temps", "Zeit", "время"}, LocStr{"to", "a", "到", "को", "إلى", "para", "à", "zu", "к"}, LocStr{"type", "tipo", "类型", "प्रकार", "نوع", "tipo", "type", "Typ", "тип"}, LocStr{"unexported", "no exportado", "未导出", "गैर-निर्यातित", "غير مصدر", "não exportado", "non exporté", "nicht exportiert", "неэкспортированный"}, LocStr{"unknown", "desconocido", "未知", "अज्ञात", "غير معروف", "desconhecido", "inconnu", "unbekannt", "неизвестный"}, LocStr{"unsigned", "sin signo", "无符号", "अहस्ताक्षरित", "غير موقع", "sem sinal", "non signé", "vorzeichenlos", "беззнаковый"}, LocStr{"use", "usar", "使用", "उपयोग", "استخدام", "usar", "utiliser", "verwenden", "использовать"}, LocStr{"valid", "válido", "有效", "वैध", "صحيح", "válido", "valide", "gültig", "действительный"}, LocStr{"validating", "validando", "验证中", "सत्यापन हो रहा है", "التحقق من", "validando", "validation", "validieren", "проверка"}, LocStr{"value", "valor", "值", "मूल्य", "قيمة", "valor", "valeur", "Wert", "значение"}, LocStr{"zero", "cero", "零", "शून्य", "صفر", "zero", "zéro", "Null", "ноль"}, }
Global dictionary instance - populated with all translations using horizontal format Language order: EN, ES, ZH, HI, AR, PT, FR, DE, RU
By using an anonymous struct, we define and initialize the dictionary in a single step, avoiding the need for a separate 'type dictionary struct' declaration. The usage API (e.g., D.Argument) remains unchanged.
var K = struct { Invalid Kind Bool Kind Int Kind Int8 Kind Int16 Kind Int32 Kind Int64 Kind Uint Kind Uint8 Kind Uint16 Kind Uint32 Kind Uint64 Kind Uintptr Kind Float32 Kind Float64 Kind Complex64 Kind Complex128 Kind Array Kind Chan Kind Func Kind Interface Kind Map Kind Pointer Kind Slice Kind String Kind Struct Kind UnsafePointer Kind }{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, }
Kind exposes the Kind constants as fields for external use, while keeping the underlying type and values private.
Functions ¶
func Contains ¶ added in v0.0.8
Contains checks if the string 'search' is present in 'conv' Returns true if found, false otherwise This matches the behavior of the standard library strings.Contains
func Convert ¶
func Convert(v ...any) *conv
Convert initializes a new conv struct with optional value for string,bool and number manipulation. REFACTORED: Now accepts variadic parameters - Convert() or Convert(value) Phase 7: Uses object pool internally for memory optimization (transparent to user)
func Count ¶ added in v0.1.6
Count checks how many times the string 'search' is present in 'conv' eg: "hello world" with search "world" will return 1
func Errf ¶ added in v0.1.3
Errf creates a new conv instance with error formatting similar to fmt.Errf Example: tinystring.Errf("invalid value: %s", value).Error()
func Fmt ¶ added in v0.1.3
Fmt formats a string using a printf-style format string and arguments. Example: Fmt("Hello %s", "world") returns "Hello world"
func OutLang ¶ added in v0.1.3
func OutLang(l ...any)
OutLang sets the default output language.
OutLang() // Auto-detects system/browser language OutLang(ES) // Set Spanish as default (using lang constant) OutLang("ES") // Set Spanish as default (using string code) OutLang("fr") // Set French as default (case-insensitive) OutLang("en-US") // Accepts locale strings, parses to EN
If a string is passed, it is automatically parsed using supported codes. If a lang value is passed, it is assigned directly. If another type is passed, nothing happens.
func T ¶ added in v0.1.3
T creates a translated string with support for multilingual translations Same functionality as Err but returns string directly instead of *conv This function is used internally by the builder API for efficient string construction
Usage examples: T(D.Format, D.Invalid) returns "invalid format" T(ES, D.Format, D.Invalid) returns "formato inválido"
Types ¶
type Kind ¶ added in v0.1.18
type Kind uint8
Kind represents the specific Kind of type that a Type represents (private) Unified with convert.go Kind, using K prefix for TinyString naming convention.
IMPORTANT: The order and values of Kind must NOT be changed. These values are used in tinyreflect, a minimal version of reflectlite from the Go standard library. Keeping the order and values identical ensures compatibility with code and data shared between tinystring and tinyreflect.
type LocStr ¶ added in v0.1.4
type LocStr [9]string
LocStr represents a string with translations for multiple languages.
It is a fixed-size array where each index corresponds to a language constant (EN, ES, PT, etc.). This design ensures type safety and efficiency, as the compiler can verify that all translations are provided.
The order of translations must match the order of the language constants.
Example of creating a new translatable term for "File":
var MyDictionary = struct { File LocStr }{ File: LocStr{ EN: "file", ES: "archivo", ZH: "文件", HI: "फ़ाइल", AR: "ملف", PT: "arquivo", FR: "fichier", DE: "Datei", RU: "файл", }, }
Usage in code:
err := Err(MyDictionary.File, D.Not, D.Found) // -> "file not found", "archivo no encontrado", etc.
Source Files
¶
- bool.go
- builder.go
- capitalize.go
- compact_float.go
- contain.go
- convert.go
- dictionary.go
- env.back.go
- error.go
- fmt_number.go
- fmt_precision.go
- fmt_template.go
- join.go
- kind.go
- language.go
- mapping.go
- memory.go
- num_float.go
- num_int.go
- parse.go
- quote.go
- repeat.go
- replace.go
- sci_format.go
- split.go
- translation.go
- truncate.go
- wr_uintbase.go