亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何讓 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 關注
  • 100 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號