5

In python one can use f-string to format strings like this

name1 = 'Ele'
name2 = 'Ben'
name3 = 'Frank'
age = 45

print(f"My name is {name1} but I also get called {name2} and at times {name3}. Generally I prefer {name1} and my age is {age}")

what is golang's equivalent to this? where I can specify exactly which variable at what spot

currently this is all I see with golang, but it creates repeating variables unnecessarily like below

name1 := "Ele"
name2 := "Ben"
name3 := "Frank"
age := 45

message := fmt.Sprintf("My name is %s but I also get called %s and at times %s. Generally I prefer %s and my age is %d", name1, name2, name3, name1, age)

fmt.Println(message)

Imagine if I need to repeat a variable multiple times in the same string, I will have to keep repeating it and then need to monitor the position of the variable always to make sure they align correctly

Is there a way similar to f-string in python for golang?

3
  • 2
    Go does not have a feature like Python’s f-string. Commented Jan 16, 2022 at 5:37
  • so no way to specify exactly the variable? only way is to use %s and %d all over? Commented Jan 16, 2022 at 5:38
  • 1
    Before Python 3.6, that's (mainly) how it was done in Python, too. Also C and many other languages. Commented Jan 16, 2022 at 5:40

2 Answers 2

1

You can use text/template.

It's a bit overkill for this simple example, but it can be worth the overhead when dealing with complex templates, lots of output, etc.

package main

import (
    "bytes"
    "fmt"
    "log"
    "text/template"
)

func main() {
    data := fdata{
        "Name1": "Ele",
        "Name2": "Ben",
        "Name3": "Frank",
        "Age":   45,
    }
    format := "My name is {{.Name1}} but I also get called {{.Name2}} and at times {{.Name3}}. Generally I prefer {{.Name1}} and my age is {{.Age}}."

    result, err := fstring(format, data)
    if err != nil {
        log.Fatalf("fstring() failed: %v", err)
    }

    fmt.Println(result)
}

type fdata map[string]interface{}

func fstring(format string, data fdata) (string, error) {
    t, err := template.New("fstring").Parse(format)
    if err != nil {
        return "", fmt.Errorf("error creating template: %v", err)
    }
    output := new(bytes.Buffer)
    if err := t.Execute(output, data); err != nil {
        return "", fmt.Errorf("error executing template: %v", err)
    }
    return output.String(), nil
}

Output:

My name is Ele but I also get called Ben and at times Frank. Generally I prefer Ele and my age is 45.

Go Playground

Sign up to request clarification or add additional context in comments.

2 Comments

pretty good!..in the situation where i just need the string with the formatted variable values, how can i get the final string generated the fastest/simplest way? seems i have to go through multiple lines of code for your answer
You can compartmentalize the interaction with text/template by implementing a helper function. And you can use a map instead of struct. (I've updated the answer to demonstrate these). But at the end of the day, Go isn't Python, so feature parity isn't a given and the code to accomplish a given task will be different.
0

I have used fmt.Println("My name is " + name), I have declared var name prior as my name and it worked. But I tried doing fmt.Print("My name is " + name "and my age is" + age) which is creating an error

Edit: I got this as in go lang you cannot use string with an int, so you have to write as:

package main

import "fmt"

func main() {
    //var name string = "Srijit"
    var name string = "Srijit"
    fmt.Println("My name is " + name)
    name = "Sam"
    fmt.Println("My name is " + name)

    num := 23

    fmt.Println("My name is "+name, "and my age is", num)
}

See I have changed +num to ,num (it does not allow string to num)

1 Comment

fmt.Print("My name is " + name "and my age is" + age) creates an error because it is invalid syntax. You correctly place a + in front of name, but you failed to place a + after name. In contrast, this works: fmt.Println("My name is "+name+" and my age is", num)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.