登录
首页 >  Golang >  Go问答

在不应该被调用的时候,首先调用Go语言的else语句

来源:stackoverflow

时间:2024-02-04 19:51:43 169浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《在不应该被调用的时候,首先调用Go语言的else语句》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

// 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语言的else语句》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>