fstr

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2024 License: MIT Imports: 5 Imported by: 0

README

fstr

Build and Test fstr Go 1.21.5

A simple Go package for string interpolation, inspired by Python's f-strings.

Overview

The fstr package provides a straightforward way to interpolate variables into strings. It's designed to be an intuitive tool for Go developers looking to embed dynamic expressions inside string literals.

Features

  • Easy to use with a simple API.
  • Supports dynamic string interpolation similar to Python's f-strings.

Installation

To install fstr, simply run:

go get github.com/ZiadMansourM/fstr

Usage

package main

import (
    "fmt"
    "github.com/ZiadMansourM/fstr"
)

func main() {
    // Standard string interpolation with formatting
    fmt.Println(fstr.Eval(
        "Hello, {name}! This is {person} {age} years old. With {balance:,.2f} USD in the bank. With GPA of {gpa:.2f}.",
        map[string]interface{}{
            "name":    "World",
            "person":  "John Doe",
            "age":     23,
            "balance": 123456789.64789,
            "gpa":     3.57869,
        },
    ))
    // Output:
    // Hello, World! This is John Doe 23 years old. With 123,456,789.65 USD in the bank. With GPA of 3.58.
    
    // Extended syntax for key-value pairing
    fmt.Println(fstr.Eval(
        "{name=} {age=} {gpa=:,.2f} {total=:,.3f}",
        map[string]interface{}{
            "name":  "Ziad Mansour",
            "age":   23,
            "gpa":   3.1495,
            "total": 123456789.9787968,
        },
    ))
    // Output:
    // name=Ziad Mansour age=23 gpa=3.15 total=123,456,789.979
}

Contributing

Contributions are welcome! Feel free to submit pull requests, create issues, or provide feedback.

Documentation

Overview

Package fstr, akin to Python's f-strings, is a Go utility that simplifies string formatting with interpolation. It seamlessly integrates expressions into string literals for dynamic construction, enhancing readability and efficiency in string formatting. This package introduces primary functions: `Interpolate`, `Eval`, `Print`, and `Println`.

Interpolate: The `Interpolate` function replaces placeholders within a string with values from a provided map. It supports simple placeholders (e.g., {key}) and formatted placeholders (e.g., {key:.2f}) for various formatting options. This function is useful for when you need the interpolated string returned for further processing.

Example of `Interpolate` usage:

var template = "Hello {name}, your balance is {balance:.2f}"
var data = map[string]interface{}{"name": "John Doe", "balance": 123.456}
if message, err := fstr.Interpolate(template, data); err == nil {
	fmt.Println(message) // Output: "Hello John Doe, your balance is 123.46"
}

Eval: The `Eval` function is a convenience wrapper around `Interpolate`. It evaluates the string with embedded expressions directly and returns the formatted string or panics if there's an error. This is useful for quick scripts or applications where error handling isn't critical.

Example of `Eval` usage:

fmt.Println(fstr.Eval(
	"Welcome {name}, your registration is {status}.",
	map[string]interface{}{
		"name": "Jane Doe",
		"status": "complete",
	}
)) // Output: "Welcome Jane Doe, your registration is complete."

Print and Println: The `Print` and `Println` functions extend the concept of `Eval` by directly printing the formatted string to standard output. `Print` does not add a newline after the output, whereas `Println` does. These functions are convenient for direct output scenarios.

Example usage of `Println`:

fstr.Println(
	"Good day, {name}! Your score is {score}.",
	map[string]interface{}{
		"name": "Alice",
		"score": 92,
	}
) // Output: "Good day, Alice! Your score is 92."

Both `Interpolate` and `Eval`, along with the printing functions, are invaluable for generating dynamic text where the template remains consistent, but the data changes, facilitating ease of maintenance and clarity in code involving string operations.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Eval added in v0.0.6

func Eval(format string, data map[string]interface{}) string

Eval is a convenience wrapper around Interpolate. It takes a format string and a data map, interpolates the format string with values from the data map, and returns the result. If an error occurs during interpolation, Eval panics with that error.

Use Eval when you want a simple way to use string interpolation without handling errors each time. It's especially useful in scenarios where you're sure the format string and data won't cause errors, or in quick scripts or applications where error handling isn't critical. For more robust applications, consider using Interpolate directly and handling errors appropriately.

Parameters:

  • format: A string with placeholders to be replaced by values from the data map. Placeholders are in the form {key} or {key:format}.
  • data: A map[string]interface{} where each key corresponds to a placeholder in the format string, and the associated value is what you want to replace the placeholder with.

Returns:

  • A string with all placeholders replaced by corresponding data values.

Panics:

  • If an error occurs during interpolation, Eval panics with the error returned by Interpolate.

Example usage:

result := fstr.Eval("Hello, {name}!", map[string]interface{}{"name": "Alice"})
fmt.Println(result) // Prints: Hello, Alice!

func Interpolate

func Interpolate(format string, data map[string]interface{}) (string, error)

Interpolate performs string interpolation on the provided format string using the given data map. It replaces placeholders in the format like {key} or {key:format} with corresponding values from the data map.

The function supports:

  • Simple placeholders like {key} which are replaced by the value of 'key' from the data map.
  • Formatted placeholders like {key:.2f} or {key:,} which are replaced with the value formatted according to the specifier.

The function uses Go's text/template package for template processing and supports custom formatting through the formatNumber function.

Arguments:

  • format: The format string containing placeholders.
  • data: A map of keys and values used to replace placeholders in the format string.

Returns:

  • The interpolated string or an error if the template parsing or execution fails.

func Print added in v1.0.0

func Print(format string, data map[string]interface{})

Print is a convenience wrapper around Eval. It takes a format string and a data map, interpolates the format string with values from the data map, and prints the result to stdout. If an error occurs during interpolation, Print panics with that error.

func Println added in v1.0.0

func Println(format string, data map[string]interface{})

Println is a convenience wrapper around Eval. It takes a format string and a data map, interpolates the format string with values from the data map, and prints the result to stdout. If an error occurs during interpolation, Println panics with that error.

Types

This section is empty.

Jump to

Keyboard shortcuts

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