github.com/enetx/g@v1.0.80/format.go (about)

     1  package g
     2  
     3  import "fmt"
     4  
     5  // Sprintf formats according to a format specifier and returns the resulting String.
     6  func Sprintf[T ~string](str T, a ...any) String { return NewString(fmt.Sprintf(string(str), a...)) }
     7  
     8  // Sprint formats using the default formats for its operands and returns the resulting String.
     9  // Spaces are added between operands when neither is a string.
    10  func Sprint(a ...any) String { return NewString(fmt.Sprint(a...)) }
    11  
    12  // Format formats a string (str) by replacing placeholders with values from a map (args)
    13  // and returns the result as a String. Placeholders in the format string should be enclosed
    14  // in curly braces, e.g., "{name}". The values for placeholders are retrieved from the
    15  // provided map using Sprint for formatting individual values.
    16  //
    17  // Parameters:
    18  //   - str: A format specifier as a template for the formatting.
    19  //   - args: A map containing values to replace placeholders in the format specifier.
    20  //
    21  // Returns:
    22  //
    23  //	A String containing the formatted result.
    24  //
    25  // Example:
    26  //
    27  //	values := map[string]any{
    28  //	    "name":  "John",
    29  //	    "age":   30,
    30  //	    "city":  "New York",
    31  //	}
    32  //	format := "Hello, my name is {name}. I am {age} years old and live in {city}."
    33  //	formatted := g.Format(format, values)
    34  //	formatted.Print()
    35  //
    36  // Output:
    37  //
    38  //	Hello, my name is John. I am 30 years old and live in New York.
    39  func Format[T, U ~string](str T, args Map[U, any]) String {
    40  	result := String(str)
    41  
    42  	args.Iter().
    43  		ForEach(
    44  			func(k U, v any) {
    45  				result = result.ReplaceAll("{"+String(k)+"}", Sprint(v))
    46  			})
    47  
    48  	return result
    49  }