Standard library / go/types
go/types.Eval()
Type-checks an expression in a package context; returns type and exact constant value when available. It does not execute source code. Expected stdout: 'untyped int 5\n'.
Formal Syntax & Structure
go syntaxgo
func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (_ TypeAndValue, err error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| fset | *token.FileSet | File set used to parse source. |
| pkg | *Package | Package containing the symbol; nil for package-independent objects. |
| pos | token.Pos | Source position in the associated file set. |
| expr | string | Expression source text or parsed expression. |
Return Value
(_ TypeAndValue, err error)
Type-checks an expression in a package context; returns type and exact constant value when available.
Working Example
Example Snippetgo
package main
import ( "fmt" "go/token" "go/types")
func check(e error) { if e != nil { panic(e) }}
func main() { tv, err := types.Eval(token.NewFileSet(), nil, token.NoPos, "2+3") check(err) fmt.Println(tv.Type, tv.Value.ExactString())}