Created
February 13, 2019 22:27
-
-
Save mmcloughlin/01f01d7c3b4fc745d34d144e369679f4 to your computer and use it in GitHub Desktop.
Evaluate arithmetic expressions in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.golang.org/p/nmsmWCkwaYq