【问题标题】:How do I get the Else message to get printed only once?如何让 Else 消息只打印一次?
【发布时间】:2020-09-04 09:08:25
【问题描述】:

在下面的代码中,如果用户输入错误的 API 名称来查找 else 语句,则每次遍历 apis.Items 数组中的项目时都会打印“无法找到”消息。但我只想打印一次错误消息。就像在遍历apis.Items 数组中的所有项目之后,如果没有用户提供的名称的项目,程序应该打印“无法找到”消息。我如何做到这一点。 Ps:我是这种语言的新手

for _, item := range apis.Items {
        if item.Name == apiName {
            fmt.Printf("API ID found: %+v ", item.Id)
            api_id := item.Id 
            cmd_2, err := exec.Command("aws", "apigateway", "get-export", "--rest-api-id", api_id, "--stage-name", stageName, "--export-type", "swagger", "/home/akshitha/Documents/" + apiName + ".json").Output()
            if err != nil {
                utils.HandleErrorAndExit("Error getting API swagger", err)
            }
            output := string(cmd_2[:])
            fmt.Println(output)
            break
        }else {
            fmt.Println("Unable to fine an API with the name " + apiName)
        }

【问题讨论】:

    标签: arrays for-loop if-statement go


    【解决方案1】:

    您可以在找到item 时设置一个变量。如果没有找到则print 它outside 循环。

    像这样:

    var found bool
    
    for _, item := range apis.Items {
        if item.Name == apiName {
            fmt.Printf("API ID found: %+v ", item.Id)
            api_id := item.Id
            cmd_2, err := exec.Command("aws", "apigateway", "get-export", "--rest-api-id", api_id, "--stage-name", stageName, "--export-type", "swagger", "/home/akshitha/Documents/"+apiName+".json").Output()
            if err != nil {
                utils.HandleErrorAndExit("Error getting API swagger", err)
            }
            output := string(cmd_2[:])
            fmt.Println(output)
    
            found = true
            
            break
        }
    }
    if !found {
        fmt.Println("Unable to fine an API with the name " + apiName)
    }
    
    

    【讨论】:

    • 这太棒了!又简单
    • 如果你在函数中有这个,之后没有别的,你可以只用return(而不是break),不需要found变量。
    猜你喜欢
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多