为了账号安全,请及时绑定邮箱和手机立即绑定

如何让 Else 消息只打印一次?

如何让 Else 消息只打印一次?

Go
呼如林 2022-06-27 15:49:08
在下面的代码中,如果用户输入了错误的 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)        }
查看完整描述

1 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

您可以在找到 时设置一个变量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)

}


查看完整回答
反对 回复 2022-06-27
  • 1 回答
  • 0 关注
  • 116 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号