9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

text/template上で動く計算機を作る #golang

Posted at

golangのテンプレート(例えば text/template)では、FuncMapを使うことで好きな関数を実行できます。ので練習がてら簡単な計算機を作ってみます:

package example_test

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

func ExampleTemplateCalculator() {
	funcMap := template.FuncMap{
		"add": func(a, b int) int { return a + b },
		"sub": func(a, b int) int { return a - b },
		"mul": func(a, b int) int { return a * b },
		"div": func(a, b int) int { return a / b },
	}

	var buf bytes.Buffer
	tp := template.Must(template.New("calculator").Funcs(funcMap).Parse("{{mul (div (sub 3 (add 1 4)) 2) -10}}"))
	err := tp.Execute(&buf, nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(buf.String())

	// Output:
	// 10
}

playgroundはこちら: http://play.golang.org/p/iYlS-L4qQZ

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?