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

NameTypeDescription
fset*token.FileSetFile set used to parse source.
pkg*PackagePackage containing the symbol; nil for package-independent objects.
postoken.PosSource position in the associated file set.
exprstringExpression 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())}
Go Reference