Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

groove-x
世界のどこにもない、心を満たすロボットを。私たちGROOVE Xは2015年に設立したスタートアップです。私たちの考えるロボットは、人々の生活に潤いを与える存在として、人が一緒にいたくなるような新世代の家庭用ロボットです。便利さや機能性ではなく、家族や伴侶として愛される存在になれるかどうか。 GROOVE Xが追求するのはあなたの感性の領域に訴えるロボットです。
https://groove-x.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした