GO語言"go/scanner"包中"Scanner.Scan"類型的用法及代碼示例。
用法:
func(s *Scanner) Scan()(pos token.Pos, tok token.Token, lit string)
Scan 掃描下一個標記並返回標記位置、標記及其文字字符串(如果適用)。源端由 token.EOF 表示。
如果返回的標記是文字(token.IDENT、token.INT、token.FLOAT、token.IMAG、token.CHAR、token.STRING)或 token.COMMENT,則文字字符串具有相應的值。
如果返回的標記是關鍵字,則文字字符串就是關鍵字。
如果返回的標記是 token.SEMICOLON,如果分號存在於源中,則相應的文字字符串是 ";",如果分號是由於換行符或在 EOF 處插入的,則為 "\n"。
如果返回的標記是 token.ILLEGAL,則文字字符串是違規字符。
在所有其他情況下,Scan 返回一個空的文字字符串。
對於更寬容的解析,即使遇到語法錯誤,Scan 也會盡可能返回有效令牌。因此,即使生成的令牌序列不包含非法令牌,客戶端也可能不會假設沒有發生錯誤。相反,它必須檢查掃描儀的ErrorCount 或錯誤處理程序的調用次數(如果已安裝)。
Scan 將行信息添加到使用 Init 添加到文件集中的文件中。令牌位置相對於該文件,因此相對於文件集。
例子:
package main
import (
"fmt"
"go/scanner"
"go/token"
)
func main() {
// src is the input that we want to tokenize.
src := []byte("cos(x) + 1i*sin(x) // Euler")
// Initialize the scanner.
var s scanner.Scanner
fset := token.NewFileSet() // positions are relative to fset
file := fset.AddFile("", fset.Base(), len(src)) // register input "file"
s.Init(file, src, nil /* no error handler */, scanner.ScanComments)
// Repeated calls to Scan yield the token sequence found in the input.
for {
pos, tok, lit := s.Scan()
if tok == token.EOF {
break
}
fmt.Printf("%s\t%s\t%q\n", fset.Position(pos), tok, lit)
}
}
輸出:
1:1 IDENT "cos" 1:4 ( "" 1:5 IDENT "x" 1:6 ) "" 1:8 + "" 1:10 IMAG "1i" 1:12 * "" 1:13 IDENT "sin" 1:16 ( "" 1:17 IDENT "x" 1:18 ) "" 1:20 ; "\n" 1:20 COMMENT "// Euler"
相關用法
- GO Scanner.Bytes用法及代碼示例
- GO Scanner用法及代碼示例
- GO Scope用法及代碼示例
- GO StreamWriter用法及代碼示例
- GO Split用法及代碼示例
- GO Server.Shutdown用法及代碼示例
- GO Slice用法及代碼示例
- GO StructTag.Lookup用法及代碼示例
- GO SplitAfter用法及代碼示例
- GO Sum256用法及代碼示例
- GO SectionReader用法及代碼示例
- GO Sin用法及代碼示例
- GO Sprintf用法及代碼示例
- GO Strings用法及代碼示例
- GO SendMail用法及代碼示例
- GO StructTag用法及代碼示例
- GO Stmt用法及代碼示例
- GO Sprint用法及代碼示例
- GO SpecialCase用法及代碼示例
- GO SectionReader.ReadAt用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Scanner.Scan。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。