8
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

Organization

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

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

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
8
Help us understand the problem. What are the problem?