import ( "fmt" "go/scanner" "go/token" "strings" ) func main() { var src = ` package main import "fmt" func main() { fmt.Println("Hello, world!") } ` var s scanner.Scanner s.Init(token.NewFileSet(), strings.NewReader(src), nil, scanner.ScanComments) for { pos, tok, lit := s.Scan() if tok == token.EOF { break } fmt.Printf("Token Position: %s | Token Type: %s | Token Literal: %q\n", pos, tok, lit) } }
import ( "fmt" "go/scanner" "strings" ) func main() { var src = "1 + 2 * 3" var s scanner.Scanner s.Init(strings.NewReader(src)) for { pos, tok, lit := s.Scan() if tok == scanner.EOF { break } fmt.Printf("Token Position: %s | Token Type: %s | Token Literal: %q\n", pos, tok, lit) } }Description: In this code example, we use the Scanner package to tokenize a mathematical expression: `1 + 2 * 3`. The scanner is initialized with the source code, and each token is scanned and printed to the console. This snippet is an example of how the Go Scanner package can be used to tokenize any input source. Package Library: Go Scanner is a built-in library of the Go Programming Language.