String interpolation in golang

Ly Channa
1 min readOct 26, 2018

--

If you are from a dynamic language, you might have written string interpolations, for example, something like this in PHP

// PHP string interpolation
“${year}-${month}-${day}”

or in Ruby as below

# Ruby string interpolation
“#{year}-#{month}-#{day}”

you might question how to do this in Go language?

How to achieve string interpolation in Go?

The Go Sprintf method from fmt package serves just this:

String Interpolation.

You might wonder why it can not be as short as in Ruby or PHP?

If you see the example from PHP or Ruby, you might realize that they are more for dynamic type system because it does care about what you pass into the interpolation string — the data types of year, month and day, however in a static, compiled language like Go, we need to specify types of our variables.

Conclusion

It might look weird to you, but if you think about the benefit of static type language with compile-time error checking, this makes a lot of sense, more convenient and easy to debug than string interpolation in dynamic languages.

--

--

Ly Channa
Ly Channa

Written by Ly Channa

Highly skilled: REST API, OAuth2, OpenIDConnect, SSO, TDD, RubyOnRails, CI/CD, Infrastruct as Code, AWS.

Responses (11)