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

在下面的代码中,如果用户输入了错误的 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)

        }


呼如林
浏览 117回答 1
1回答

哔哔one

您可以在找到 时设置一个变量item。如果找不到,则print循环outside。像这样:var found boolfor _, 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)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go