tinystring

package module
v0.1.58 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 7, 2025 License: MIT Imports: 4 Imported by: 14

README

TinyString

Project Badges

TinyString is a lightweight Go library that provides comprehensive string manipulation, type conversion, formatting, and multilingual error handling with a fluid API, specifically designed for small devices and web applications using TinyGo as the target compiler.

Key Features

  • 🚀 Fluid and chainable API - Easy to use and readable operations
  • 📝 Complete string toolkit - Transformations, conversions, formatting, and error handling
  • 🌍 Multilingual error messages - Built-in dictionary system with 9 languages
  • 🧵 Concurrency safe - Thread-safe operations for concurrent environments
  • 📦 Zero dependencies - No fmt, strings, strconv, or errors imports
  • 🎯 TinyGo optimized - Manual implementations for minimal binary size
  • 🌐 WebAssembly-first - Designed for modern web deployment
  • 🔄 Universal type support - Works with strings, numbers, booleans, and slices
  • Performance focused - Predictable allocations and custom optimizations

Why TinyString?

Installation

go get github.com/cdvelop/tinystring

Usage

import . "github.com/cdvelop/tinystring"

// Quick start - Basic conversion and transformation
text := Convert("Hóla Múndo").Tilde().ToLower().String() // out: "hola mundo"

// Working with different data types
numText := Convert(42).String()     // out: "42"
boolText := Convert(true).String()  // out: "true"

// Memory-efficient approach using string pointers
original := "Él Múrcielago Rápido"
Convert(&original).Tilde().CamelLow().Apply()
// original is now: "elMurcielagoRapido"

// Efficient, Unified builder and chaining example usage in loops and reuse, with accent normalization (Tilde)
items := []string{"  ÁPPLE  ", "  banána  ", "  piñata  ","  ÑANDÚ  "}
builder := Convert() // without params reused buffer = optimal performance
for i, item := range items {
    processed := Convert(item).
        TrimSpace(). // TrimSpace whitespace
        Tilde(). // Normalize accents
        ToLower(). // Convert to lowercase
        Capitalize(). // Capitalize first letter
        String() // Finalize the string
    builder.Write(processed)
    if i < len(items)-1 {
        builder.Write(" - ")
    }
}

out := builder.String() // Finalize the string hiding the error
out, err := builder.StringErr() // OR finalize with error handling

// out: "Apple - Banana - Piñata - Ñandu", err: nil

📚 Standard Library Equivalents

🔤 strings Package

Replace common strings package functions with TinyString equivalents:

Go Standard TinyString Equivalent
strings.Builder c:= Convert() c.Write(a) c.Write(b) c.String()
strings.Contains() Contains(s, substr)
strings.Index() Index(s, substr)
strings.LastIndex() LastIndex(s, substr)
strings.Join() Convert(slice).Join(sep).String()
strings.Repeat() Convert(s).Repeat(n).String()
strings.Replace() Convert(s).Replace(old, new).String()
strings.Split() Convert(s).Split(sep).String()
strings.ToLower() Convert(s).ToLower().String()
strings.ToUpper() Convert(s).ToUpper().String()
strings.TrimSpace() Convert(s).TrimSpace().String()
strings.TrimPrefix() Convert(s).TrimPrefix(prefix).String()
strings.TrimSuffix() Convert(s).TrimSuffix(suffix).String()
Other String Transformations
Convert("hello world").CamelLow().String() // out: "helloWorld"
Convert("hello world").CamelUp().String()  // out: "HelloWorld"
Convert("hello world").SnakeLow().String() // out: "hello_world"
Convert("hello world").SnakeUp().String()  // out: "HELLO_WORLD"
String Search & Operations
// Search and count
pos := Index("hello world", "world")                  // out: 6 (first occurrence)
found := Contains("hello world", "world")              // out: true
count := Count("abracadabra", "abra")       // out: 2

// Find last occurrence (useful for file extensions)
pos := LastIndex("image.backup.jpg", ".")             // out: 12
if pos >= 0 {
    extension := "image.backup.jpg"[pos+1:]           // out: "jpg"
}

// ⚠️ Note: Index, Contains and LastIndex are global functions, not methods.
// Do NOT use: Convert(s).Contains(substr) // ❌ Incorrect, will not compile
// Use:        Index(s, substr)            // ✅ Correct
//             Contains(s, substr)         // ✅ Correct
//             LastIndex(s, substr)        // ✅ Correct

// Replace operations
Convert("hello world").Replace("world", "Go").String() // out: "hello Go"
Convert("test 123 test").Replace(123, 456).String()    // out: "test 456 test"
String Splitting & Joining
// Split strings (always use Convert(...).Split(...))
parts := Convert("apple,banana,cherry").Split(",")
// out: []string{"apple", "banana", "cherry"}

parts := Convert("hello world new").Split()  // Handles whitespace
// out: []string{"hello", "world", "new"}

// Join slices
Convert([]string{"Hello", "World"}).Join().String()    // out: "Hello World"
Convert([]string{"a", "b", "c"}).Join("-").String()    // out: "a-b-c"
String Trimming & Cleaning
// TrimSpace operations
Convert("  hello  ").TrimSpace().String()                    // out: "hello"
Convert("prefix-data").TrimPrefix("prefix-").String()   // out: "data"
Convert("file.txt").TrimSuffix(".txt").String()         // out: "file"

// Repeat strings
Convert("Go").Repeat(3).String()                        // out: "GoGoGo"
🔢 strconv Package

Replace strconv package functions for type conversions:

Go Standard TinyString Equivalent
strconv.Itoa() Convert(i).String()
strconv.Atoi() Convert(s).Int()
strconv.ParseFloat() Convert(s).Float64()
strconv.ParseBool() Convert(s).Bool()
strconv.FormatFloat() Convert(f).Round(n).String()
strconv.Quote() Convert(s).Quote().String()
Type Conversions
// String to numbers => Int,Int32,Int64,Uint,Uint32,Uint64,Float32,Float64 eg:
result, err := Convert("123").Int()        // out: 123, nil
result, err := Convert("456").Uint()       // out: 456, nil  
result, err := Convert("3.14").Float64()     // out: 3.14, nil

// Numbers to string
Convert(42).String()      // out: "42"
Convert(3.14159).String() // out: "3.14159"

// Boolean conversions
result, err := Convert("true").Bool()  // out: true, nil
result, err := Convert(42).Bool()      // out: true, nil (non-zero = true)
result, err := Convert(0).Bool()       // out: false, nil

// String quoting
Convert("hello").Quote().String()           // out: "\"hello\""
Convert("say \"hello\"").Quote().String()  // out: "\"say \\\"hello\\\"\""
Number Formatting
// Decimal rounding: keep N decimals, round or truncate
// By default, rounds using "round half to even" (bankers rounding)
// Pass true as the second argument to truncate (no rounding), e.g.:
Convert("3.14159").Round(2).String()        // "3.14" (rounded)
Convert("3.155").Round(2).String()          // "3.16" (rounded)
Convert("3.14159").Round(2, true).String()  // "3.14" (truncated, NOT rounded)
Convert("3.159").Round(2, true).String()    // "3.15" (truncated, NOT rounded)

// Formatting with thousands separator (EU default)
Convert(2189009.00).Thousands().String()        // out: "2.189.009"
// Anglo/US style (comma, dot)
Convert(2189009.00).Thousands(true).String()    // out: "2,189,009"
🖨️ fmt Package

Replace fmt package functions for formatting:

Go Standard TinyString Equivalent
fmt.Sprintf() Fmt(format, args...)
fmt.Sprint() Convert(v).String()
fmt.Fprintf() Fprintf(w, format, args...)
fmt.Sscanf() Sscanf(src, format, args...)
String Formatting
// Printf-style formatting
result := Fmt("Hello %s, you have %d messages", "John", 5)
// out: "Hello John, you have 5 messages"

// Multiple format specifiers
result := Fmt("Number: %d, Float: %.2f, Bool: %v", 42, 3.14159, true)
// out: "Number: 42, Float: 3.14, Bool: true"

// Advanced formatting (hex, binary, octal)
result := Fmt("Hex: %x, Binary: %b, Octal: %o", 255, 10, 8)
// out: "Hex: ff, Binary: 1010, Octal: 10"

// Write formatted output to io.Writer
var buf bytes.Buffer
Fprintf(&buf, "Hello %s, count: %d\n", "world", 42)

// Write to file
file, _ := os.Create("output.txt")
Fprintf(file, "Data: %v\n", someData)

// Parse formatted text from string (like fmt.Sscanf)
var pos int
var name string
n, err := Sscanf("!3F question", "!%x %s", &pos, &name)
// n = 2, pos = 63, name = "question", err = nil

// Parse complex formats
var code, unicode int
var word string
n, err := Sscanf("!3F U+003F question", "!%x U+%x %s", &code, &unicode, &word)
// n = 3, code = 63, unicode = 63, word = "question", err = nil
❌ errors Package

Replace errors package functions for error handling with multilingual support:

Go Standard TinyString Equivalent
errors.New() Err(message)
fmt.Errorf() Errf(format, args...)
Error Creation
// Multiple error messages and types
err := Err("invalid format", "expected number", 404)
// out: "invalid format expected number 404"

// Formatted errors (like fmt.Errorf)
err := Errf("invalid value: %s at position %d", "abc", 5)
// out: "invalid value: abc at position 5"

🚀 TinyString Exclusive Features

🌍 TinyString: Multilingual & Translation Support

TinyString enables multilingual error messages using reusable dictionary terms. It supports 9 languages and allows global or inline language selection.

// Set and get current language code
code := OutLang(ES) // returns "ES"
code = OutLang()    // auto-detects and returns code (e.g. "EN")

err := Err(D.Format, D.Invalid)
// → "formato inválido"

// return strings
msg := Translate(FR, D.Format, D.Invalid).String()
// → "format invalide"

// Force French
err = Err(FR, D.Empty, D.String)
// → "vide chaîne"

See dictionary.go for built-in words. Combine D. (default terms) and custom dictionaries for flexible messaging.

📘 Full documentation available in docs/TRANSLATE.md

🏷️ Message Type Detection

TinyString provides automatic message type classification to help identify the nature of text content. The system detects common message types like errors, warnings, success messages, and information using zero-allocation buffer-based pattern matching.

// Before: messagetype library usage
message := Translate(msgs...).String()
msgType := messagetype.DetectMessageType(message)

// After: tinystring Single operation with StringType() (zero allocations)
message, msgType := Translate(msgs...).StringType()

// Real example - Progress callback with message classification
progressCallback := func(msgs ...any) {
    message, msgType := Translate(msgs...).StringType()
    if msgType.IsError() {
        handleError(message)
    } else {
        logMessage(message, msgType)
    }
}

// Message type constants available via Msg struct
if msgType.IsError() {
    // Handle error case
}

// Available message types:
// Msg.Normal  - Default type for general content
// Msg.Info    - Information messages  
// Msg.Error   - Error messages and failures
// Msg.Warning - Warning and caution messages
// Msg.Success - Success and completion messages

// Zero allocations - reuses existing conversion buffers
// Perfect for logging, UI status messages, and error handling
✂️ Smart Truncation
// Basic truncation with ellipsis
Convert("Hello, World!").Truncate(10).String()       
// out: "Hello, ..."

// Name truncation for UI display
Convert("Jeronimo Dominguez").TruncateName(3, 15).String()
// out: "Jer. Dominguez"

// Advanced name handling
Convert("Juan Carlos Rodriguez").TruncateName(3, 20).String()
// out: "Jua. Car. Rodriguez"
🔧 Advanced Utilities
// Key-value parsing with the new API:
value, err := Convert("user:admin").KV()            // out: "admin", nil
value, err := Convert("count=42").KV("=")          // out: "42", nil

// Struct tag value extraction (TagValue):
value, found := Convert(`json:"name" Label:"Nombre"`).TagValue("Label") // out: "Nombre", true
value, found := Convert(`json:"name" Label:"Nombre"`).TagValue("xml")   // out: "", false

Benchmarking


Contributing


License

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().ToLower().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().ToLower().String()
fmt.Println(processedText)

// Método con punteros (modifica directamente la variable original)
directText := "Otro TEXTO con ACENTOS"
Convert(&directText).Tilde().ToLower().Apply()
fmt.Println(directText)
Output:

texto con acentos
otro texto con acentos

Index

Examples

Constants

View Source
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

View Source
var D = struct {
	// A
	All        LocStr // "all"
	Allowed    LocStr // "allowed"
	Arrow      LocStr // "arrow"
	Argument   LocStr // "argument"
	Assign     LocStr // "assign"
	Assignable LocStr // "assignable"

	// B
	BackingUp LocStr // "backing up"
	Be        LocStr // "be"
	Binary    LocStr // "binary"

	// C
	Call          LocStr // "call"
	Can           LocStr // "can"
	Cannot        LocStr // "cannot"
	Cancel        LocStr // "cancel"
	Changed       LocStr // "changed"
	Character     LocStr // "character"
	Coding        LocStr // "coding"
	Compilation   LocStr // "compilation"
	Configuration LocStr // "configuration"
	Connection    LocStr // "connection"
	Content       LocStr // "content"
	Create        LocStr // "create"

	// D
	Debugging LocStr // "debugging"
	Decimal   LocStr // "decimal"
	Delimiter LocStr // "delimiter"
	Digit     LocStr // "digit"
	Down      LocStr // "down"

	// E
	Edit    LocStr // "edit"
	Element LocStr // "element"
	Empty   LocStr // "empty"
	End     LocStr // "end"
	Exceeds LocStr // "exceeds"
	Execute LocStr // "execute"

	// F
	Failed LocStr // "failed"
	Field  LocStr // "field"
	Fields LocStr // "fields"
	Files  LocStr // "files"
	Format LocStr // "format"
	Found  LocStr // "found"

	// H
	Handler LocStr // "handler"

	// I
	Icons        LocStr // "icons"
	Insert       LocStr // "insert"
	Left         LocStr // "left"
	Implemented  LocStr // "implemented"
	In           LocStr // "in"
	Index        LocStr // "index"
	Information  LocStr // "information"
	Input        LocStr // "input"
	Install      LocStr // "install"
	Installation LocStr // "installation"
	Invalid      LocStr // "invalid"

	// K
	Keyboard LocStr // "keyboard"

	// L
	Language LocStr // "language"
	Line     LocStr // "line"

	// Msg
	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"

	// N
	Negative   LocStr // "negative"
	Nil        LocStr // "null"
	NonNumeric LocStr // "non-numeric"
	Not        LocStr // "not"
	NotOfType  LocStr // "not of type"
	Number     LocStr // "number"
	Numbers    LocStr // "numbers"

	// O
	Of       LocStr // "of"
	Options  LocStr // "options"
	Out      LocStr // "out"
	Overflow LocStr // "overflow"

	// P
	Page       LocStr // "page"
	Pointer    LocStr // "pointer"
	Point      LocStr // "point"
	Preparing  LocStr // "preparing"
	Production LocStr // "production"
	Provided   LocStr // "provided"

	// Q
	Quit LocStr // "quit"

	// R
	Range    LocStr // "range"
	Read     LocStr // "read"
	Required LocStr // "required"
	Right    LocStr // "right"
	Round    LocStr // "round"

	// S
	Seconds   LocStr // "seconds"
	Session   LocStr // "session"
	Slice     LocStr // "slice"
	Space     LocStr // "space"
	Status    LocStr // "status"
	String    LocStr // "string"
	Shortcuts LocStr // "shortcuts"
	Supported LocStr // "supported"
	Switch    LocStr // "switch"
	Switching LocStr // "switching"
	Sync      LocStr // "sync"
	System    LocStr // "system"

	// Translate
	Tab     LocStr // "tab"
	Test    LocStr // "test"
	Testing LocStr // "testing"
	Text    LocStr // "text"
	Time    LocStr // "time"
	To      LocStr // "to"
	Type    LocStr // "type"

	// U
	Unexported LocStr // "unexported"
	Unknown    LocStr // "unknown"
	Unsigned   LocStr // "unsigned"
	ToUpper    LocStr // "up"
	Use        LocStr // "use"

	// V
	Valid      LocStr // "valid"
	Validating LocStr // "validating"
	Value      LocStr // "value"
	Visible    LocStr // "visible"

	// Z
	Zero LocStr // "zero"

}{}/* 114 elements not displayed */

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.

View Source
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.

View Source
var Msg = struct {
	Normal  MessageType
	Info    MessageType
	Error   MessageType
	Warning MessageType
	Success MessageType
}{0, 1, 2, 3, 4}

Msg exposes the MessageType constants for external use, following TinyString naming convention.

Functions

func Contains added in v0.0.8

func Contains(conv, search string) bool

Contains checks if the string 'search' is present in 'conv'. Uses Index internally for efficient single-pass detection.

Examples:

Contains("hello world", "world")  // returns true
Contains("hello world", "xyz")    // returns false
Contains("", "test")              // returns false (empty string)
Contains("test", "")              // returns false (empty search)
Contains("data\x00more", "\x00")  // returns true (null byte)
Contains("Case", "case")          // returns false (case sensitive)

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

func Count(conv, search string) int

Count checks how many times the string 'search' is present in 'conv'. Uses Index internally for consistency and maintainability.

Examples:

Count("abracadabra", "abra")    // returns 2
Count("hello world", "l")       // returns 3
Count("golang", "go")           // returns 1
Count("test", "xyz")            // returns 0 (not found)
Count("anything", "")           // returns 0 (empty search)
Count("a\x00b\x00c", "\x00")    // returns 2 (null bytes)

func Err added in v0.0.37

func Err(msgs ...any) *conv

func Errf added in v0.1.3

func Errf(format string, args ...any) *conv

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

func Fmt(format string, args ...any) string

Fmt formats a string using a printf-style format string and arguments. Example: Fmt("Hello %s", "world") returns "Hello world"

func Fprintf added in v0.1.49

func Fprintf(w io.Writer, format string, args ...any) (n int, err error)

Fprintf formats according to a format specifier and writes to w. It returns the number of bytes written and any write error encountered. Example: Fprintf(os.Stdout, "Hello %s\n", "world")

func Index added in v0.1.48

func Index(s, substr string) int

Index finds the first occurrence of substr in s, returns -1 if not found. This is the base primitive that other functions will reuse.

Examples:

Index("hello world", "world")  // returns 6
Index("hello world", "lo")     // returns 3
Index("hello world", "xyz")    // returns -1 (not found)
Index("hello world", "")       // returns 0 (empty string)
Index("data\x00more", "\x00")  // returns 4 (null byte)

func LastIndex added in v0.1.47

func LastIndex(s, substr string) int

LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s.

Special cases:

  • If substr is empty, LastIndex returns len(s).
  • If substr is not found in s, LastIndex returns -1.
  • If substr is longer than s, LastIndex returns -1.

Examples:

LastIndex("hello world", "world")     // returns 6
LastIndex("hello world hello", "hello") // returns 12 (last occurrence)
LastIndex("image.backup.jpg", ".")    // returns 12 (useful for file extensions)
LastIndex("hello", "xyz")             // returns -1 (not found)
LastIndex("hello", "")                // returns 5 (len("hello"))
LastIndex("", "hello")                // returns -1 (not found in empty string)

Common use case - extracting file extensions:

filename := "document.backup.pdf"
pos := LastIndex(filename, ".")
if pos >= 0 {
    extension := filename[pos+1:] // "pdf"
}

func OutLang added in v0.1.3

func OutLang(l ...any) string

OutLang sets and returns the current output language as a string.

OutLang() // Auto-detects system/browser language, returns code (e.g. "EN") OutLang(ES) // Set Spanish as default (using lang constant), returns "ES" OutLang("ES") // Set Spanish as default (using string code), returns "ES" OutLang("fr") // Set French as default (case-insensitive), returns "FR" OutLang("en-US") // Accepts locale strings, parses to EN, returns "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. Always returns the current language code as string (e.g. "EN", "ES", etc).

func Sscanf added in v0.1.54

func Sscanf(src string, format string, args ...any) (n int, err error)

Sscanf parses formatted text from a string using printf-style format specifiers. It returns the number of items successfully parsed and any error encountered. Example: Sscanf("!3F U+003F question", "!%x U+%x %s", &pos, &enc.uv, &enc.name)

func Translate added in v0.1.57

func Translate(values ...any) *conv

Translate 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: Translate(D.Format, D.Invalid) returns "invalid format" Translate(ES, D.Format, D.Invalid) returns "formato inválido" Translate creates a translated string with support for multilingual translations Same functionality as Err but returns *conv for further formatting This function is used internally by the builder API for efficient string construction

Usage examples: Translate(D.Format, D.Invalid) returns *conv with "invalid format" Translate(ES, D.Format, D.Invalid) returns *conv with "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.

func (Kind) String added in v0.1.18

func (k Kind) String() string

String returns the name of the Kind as a string

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.

type MessageType added in v0.1.54

type MessageType uint8

MessageType represents the classification of message types in the system.

func (MessageType) IsError added in v0.1.54

func (t MessageType) IsError() bool

func (MessageType) IsInfo added in v0.1.54

func (t MessageType) IsInfo() bool

func (MessageType) IsNormal added in v0.1.54

func (t MessageType) IsNormal() bool

Helper methods for MessageType

func (MessageType) IsSuccess added in v0.1.54

func (t MessageType) IsSuccess() bool

func (MessageType) IsWarning added in v0.1.54

func (t MessageType) IsWarning() bool

func (MessageType) String added in v0.1.54

func (t MessageType) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL