Pure Go string "interpolation/evaluation" package available?

745 views
Skip to first unread message

Art Mellor

unread,
Aug 27, 2014, 4:42:05 PM8/27/14
to golan...@googlegroups.com
I'm in need of a lightweight, pure Go package to do simple string evaluation/interpolation similar to what you can do in bash (but I don't want to call out to an external shell).

e.g. in bash you can do:
foo=3
bar=5
echo "Thing-$(( foo + bar * 3 ))"
Thing-18

I'd like some way to set var names in an environment and evaluate strings with some simple language embedded that would do simple substitution and arithmetic. I should be able to get by with =,+,-,*,/ as operators.

I've searched around a bit, but I think I may not be using the right keywords.

Pointers to anything like this that you know of would be greatly appreciated.

Rui Ueyama

unread,
Aug 27, 2014, 5:18:34 PM8/27/14
to Art Mellor, golang-nuts
Are "foo" and "bar" in your example all environment variable? If so, it's technically doable, although I don't think there's existing code for doing that.

If these variables are local variables in Go, it's not doable, because even if you use reflection you cannot access local variables by name.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Aston Motes

unread,
Aug 27, 2014, 5:19:03 PM8/27/14
to Art Mellor, golan...@googlegroups.com
Here's one templating library that does what you're looking for:

https://www.florian-schlachter.de/post/pongo2/

I can't vouch for the library too much as I haven't really used it, but it seems to work for your example. (http://play.golang.org/p/KXqYIqmpIW) I'm sure there are others...


On Wed, Aug 27, 2014 at 1:42 PM, Art Mellor <art.ze...@gmail.com> wrote:

--

Art Mellor

unread,
Aug 27, 2014, 5:46:38 PM8/27/14
to golan...@googlegroups.com, art.ze...@gmail.com
By environment variable I'm speaking generically, not specifically shell environment. I mean an environment specific to a session or something. I.e. state can be maintained across individual string evaluations.

Art Mellor

unread,
Aug 27, 2014, 5:46:59 PM8/27/14
to golan...@googlegroups.com, art.ze...@gmail.com
Thanks! I'll check that out.

sande...@gmail.com

unread,
Aug 27, 2014, 5:48:35 PM8/27/14
to golan...@googlegroups.com
For runtime templating you can use:

Just made a little compile time tool that might be useful:
It compiles erb style templates into pure go functions.

Best regards,
Sander Hahn
Reply all
Reply to author
Forward
0 new messages