package main import ( "fmt" "os" "text/scanner" ) func main() { file, err := os.Open("input.txt") if err != nil { panic(err) } defer file.Close() var s scanner.Scanner s.Init(file) for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() { fmt.Println(s.TokenText()) } }
package main import ( "fmt" "strings" "text/scanner" ) type Token int const ( EOF Token = iota IDENT NUMBER PLUS MINUS ) func main() { input := "x + y - 10" var s scanner.Scanner s.Init(strings.NewReader(input)) for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() { switch s.TokenText() { case "+": fmt.Println(PLUS) case "-": fmt.Println(MINUS) default: fmt.Println(IDENT) } } }In this example, we define our own set of tokens and implement a custom lexer that recognizes variables (IDENT), numbers (NUMBER), plus (+), and minus (-) symbols. We initialize the scanner with a string input, and use a switch statement to categorize each token based on its text value. This example shows how easy it is to use the scanner package to build custom language parse.