Skip to content

Instantly share code, notes, and snippets.

@mmcloughlin
Created February 13, 2019 22:27
Show Gist options
  • Select an option

  • Save mmcloughlin/01f01d7c3b4fc745d34d144e369679f4 to your computer and use it in GitHub Desktop.

Select an option

Save mmcloughlin/01f01d7c3b4fc745d34d144e369679f4 to your computer and use it in GitHub Desktop.
Evaluate arithmetic expressions in Go
package main
import (
"errors"
"go/constant"
"go/token"
"go/types"
"log"
)
func Eval(expr string) (int64, error) {
fs := token.NewFileSet()
tv, err := types.Eval(fs, nil, token.NoPos, expr)
if err != nil {
return 0, err
}
if tv.Value.Kind() != constant.Int {
return 0, errors.New("expression does not evaluate to an integer")
}
x, exact := constant.Int64Val(tv.Value)
if !exact {
return 0, errors.New("inexact result")
}
return x, nil
}
func main() {
exprs := []string{
"1",
"1<<32",
"3-2",
"true",
"1<<100",
"sdfsdfsdf<1222asdfsdf",
}
for _, expr := range exprs {
x, err := Eval(expr)
log.Printf("expr=%q x=%d err=%v", expr, x, err)
}
}
@mmcloughlin
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment