Standard library / go/types

go/types.Info.TypeOf()

Returns the type of an expression if recorded or obtainable from object information. Expected stdout: 'int\n'.

Formal Syntax & Structure

go syntaxgo
func (info *Info) TypeOf(e ast.Expr) Type

Parameters & Attributes

NameTypeDescription
east.ExprInput to the operation as described above.

Return Value

Type

Returns the type of an expression if recorded or obtainable from object information.

Working Example

Example Snippetgo
package main
import (  "fmt"  "go/ast"  "go/parser"  "go/token"  "go/types")
func check(e error) {  if e != nil {    panic(e)  }}func load() (*token.FileSet, *ast.File, *types.Package, *types.Info) {  f := token.NewFileSet()  a, e := parser.ParseFile(f, "demo.go", "package p; var X = 2+3; func F(){ x := X; _ = x }", parser.SkipObjectResolution)  check(e)  i := &types.Info{Types: map[ast.Expr]types.TypeAndValue{}, Defs: map[*ast.Ident]types.Object{}, Uses: map[*ast.Ident]types.Object{}, Scopes: map[ast.Node]*types.Scope{}}  c := types.Config{GoVersion: "go1.23"}  p, e := c.Check("demo/p", f, []*ast.File{a}, i)  check(e)  return f, a, p, i}func main() {  _, f, _, i := load()  e := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]  fmt.Println(i.TypeOf(e))}
Go Reference