Skip to Content
Hands-On Software Engineering with Golang
book

Hands-On Software Engineering with Golang

by Achilleas Anagnostopoulos
January 2020
Intermediate to advanced
640 pages
16h 56m
English
Packt Publishing
Content preview from Hands-On Software Engineering with Golang

Using tools to analyze and manipulate Go programs

Go programs are inherently easy to parse. In fact, the Go library provides built-in packages that can parse Go programs into abstract syntax trees (ASTs), which can be traversed, modified, and transformed back into Go code. Let's go through a simple example to show you how easy it is to work with these packages.

First, we need a helper function to convert a Go program into an AST representation. The following parse function does exactly that:

import (
    "fmt"
    "go/ast"
    "go/parser"
    "go/token"
)

// parse a Go program into an AST representation.
func parse(program string) (*token.FileSet, *ast.File, error) {
    fs := token.NewFileSet()
    tree, err := parser.ParseFile(fs, "example.go", program, 0)
    
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Hands-On Software Architecture with Golang

Hands-On Software Architecture with Golang

Jyotiswarup Raiturkar

Publisher Resources

ISBN: 9781838554491Supplemental Content