
Go语言中的else语句在不应该被调用的情况下会被优先执行,这是一个常见的错误现象。else语句通常用来处理条件不满足的情况,但是在某些情况下,由于代码逻辑错误或者程序流程控制错误,else语句会被错误地执行。这种情况下,程序的行为可能会出现错误,导致程序运行结果不符合预期。php小编香蕉在这篇文章中将为您详细介绍这个问题的原因以及解决方法,帮助您更好地理解和避免这个常见的错误。
// Invalid token found, print error message and exit.
func abort(message string) {
panic(message)
}
// Skip whitespace except newlines, which we will use to indicate the end of a statement.
func (s *Source) skipWhitespace() {
for s.curChar == " " || s.curChar == "\t" || s.curChar == "\r" {
s.nextChar()
}
}
// Skip comments in the code.
func skipComment() {}
// Return the next token.
func (s *Source) getToken() Token {
var token Token
// Check the first character of this token to see if we can decide what it is.
// If it is a multiple character operator (e.g., !=), number, identifier, or keyword then we will process the rest.
// s.skipWhitespace()
println("curChar: " + s.curChar)
s.skipWhitespace()
println("curChar: after 84 " + s.curChar)
if s.curChar == "+" {
token = Token{s.curChar, PLUS}
} else if s.curChar == "-" {
token = Token{s.curChar, MINUS}
} else if s.curChar == "*" {
token = Token{s.curChar, ASTERISK}
} else if s.curChar == "/" {
token = Token{s.curChar, SLASH}
} else if s.curChar == "\n" {
token = Token{s.curChar, NEWLINE}
} else if s.curChar == "\000" {
token = Token{s.curChar, EOF}
} else {
println("Unknown token: " + s.curChar)
}
s.nextChar()
return token
}
// Process the next character.
func (s *Source) nextChar() {
s.curPos++
if s.curPos >= len(s.source) {
s.curChar = "\000" // EOF
} else {
s.curChar = string(s.source[s.curPos])
}
}
func do_lexing(codeString string) { // code_string = `+- */`
// Initialize the source.
source := Source{source: codeString + "\n", curChar: "", curPos: -1}
// Loop through and print all tokens.
token := source.getToken()
println(token.text, token.kind, "token 119")
for token.kind != EOF {
println(token.text, token.kind)
token = source.getToken()
}
}输出为
curChar: curChar: after 84 Unknown token: 0 token 199 0 curChar: + curChar: after 84 + + 202 curChar: - curChar: after 84 - - 203 curChar: curChar: after 84 * * 204 curChar: / curChar: after 84 / / 205 curChar: curChar: after 84 0 curChar: curChar: after 84
它应该首先打印 + 和 - 令牌,然后将未知令牌打印到终端,但它首先打印未知令牌,然后打印所有其他令牌..我可能错过了一些东西。我是 golang 新手。 println(token.text, token.kind, "令牌 119") 此行也不会首先打印
我尝试添加打印语句
您在上述 println 语句之前首先调用 getToken,并且 getToken 有自己的 println 调用,因此不首先打印“token 199”是合乎逻辑的。
不,不应该。您正在调用 getToken ,它调用 skipWhitespace ,它调用 nextChar ONLY IF curChar 是空格,但 curChar 是 "" (空字符串,不是空格)开头你的程序的。输出反映了实现。
以上就是Go lang else 在不应该被调用的时候被首先调用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号