SoFunction
Updated on 2025-03-05

Learning from Rust Go to consider simple string interpolation characteristics example analysis

Or write assembled string business

In daily development Go projects, we often useorGo to write similar assembled strings.

The following code:

("Hello Gopher %s, you are %d years old and you're favorite food is %s", name, age, favoriteFood)

This business iterates and iterates over time, and some of the often changing assembly logic will become longer and longer. The small computer display is no longer enough to let the code be displayed in one line.

There are many features that convert strings into variables, but the string of stinky and long variables cannot be simply removed, so most students choose to format the code.

The following code:

s :=  "Hello Gopher %s, you are %d years old and you're favorite food is %s"
(
    s, 
    name, 
    age, 
    favoriteFood,
)

You might think this is an example? Actually, it's not, many people have encountered it.

Simple string interpolation

This has been discussed in the community for three or four years in Go issues, and @Ian Lance Taylor initiated a new proposalproposal: spec: add simple string interpolation similar to Swift》。

I hope to get more discussion and add new features to solve this problem.

This new feature is similar to a simple version of string interpolation in Swift. Let's look at the example directly:

("\(()) is \(()) years old")
("The time is \(().Round(0))")

Corresponding output results:

Ken Thompson is 79 years old

The time is 2023-01-04 16:22:01.204034106 -0800 PST

The new "string interpolation" added to the proposal plan is as follows:

  • New escape syntax:\(xxxx), the beginning is\(, the ending is), appear in pairs.
  • In the format, a valid\(, there must be an expression and a trailing one after the end, so that it can take effect.

In the above example, the following are string interpolation:

\(())
\(())
\(().Round(0))

There will be some students who are confused.personHow does it look like a structure take the value?

Go has a magical convention method, such as structures, if there isString() stringmethod, this method will be called to get the string value.

If there is no String method, it needs to be a type of string, integer, floating point, complex, constant or boolean, etc., and can be formatted after taking the value. Otherwise, an error will be reported.

Other language examples

Swift

let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"

Kotlin

var age = 21
println("My Age Is: $age")

C

string name = "Mark";
var date = ;
($"Hello, {name}! Today is {}, it's {date:HH:mm} now.");

Rust

let person = get_person();
println!("Hello, {person}!"); // captures the local `person`
println!("Hello, {}!", get_person());                // implicit position
println!("Hello, {0}!", get_person());               // explicit index
println!("Hello, {person}!", person = get_person()); // named
let (width, precision) = get_format();
for (name, score) in get_scores() {
  println!("{name}: {score:width$.precision$}");
}

Dispute and contradictory points

One of the main debate points at present is likeand other methods can also achieve the same effect of string interpolation. Why do you need to add this functional feature (or syntax sugar)?

The mainstream view is the existing method of formatting strings. After the number of parameters is too high, it is easy to make mistakes (for example: wrong order), and it is relatively loose, and it is a lot of code.

After adding the feature/synthetic sugar of string interpolation, you can read and modify it better without relying too much on the order of writing variables and being more compact.

Specific examples are as follows, the existing version code:

errorf(pos, "arguments to copy %s and %s have different element types %s and %s", x, &y, , )

After applying the new feature, it will become:

error(pos, "arguments to copy \(x) and \(&y) have different element types \() and \()")

Summarize

In fact, we often encounter this problem at work, and even in issues, some classmates reported that they often have to write format parameters of more than 50 parameters, which is more painful to maintain in Go.

If you are a developer who maintains several projects for a long time, you will continue to add and change existing formatted string methods and add new string interpolation.

Which one would you choose in the next few years? Or are there any new ideas?

The above is the detailed content of the example analysis of the Go to consider the simple string interpolation feature from Rust. For more information about Rust Go simple string interpolation, please pay attention to my other related articles!