2 回答

TA貢獻1818條經驗 獲得超8個贊
試試這個
...
splitted := strings.Split(file.Name(), ".")
lenSplit := len(splitted)
if lenSplit > 1 && splitted[lenSplit-1] == "rpm" {
// file with extension
}
...
用“.”分割文件名
轉到字符串數組中的最后一個字符串
檢查最后一個字符串是否匹配“rpm”

TA貢獻2012條經驗 獲得超12個贊
.rpm在任何一次迭代中都無法判斷是否沒有文件具有擴展名。您只能在檢查所有文件后才能確定。
因此,與其嘗試將其壓縮到循環中,不如維護一個found變量,您可以在.rpm找到文件時對其進行更新。
found := false // Assume false for now
for _, file := range files {
if file.Mode().IsRegular() {
if filepath.Ext(file.Name()) == ".rpm" {
// Process rpm file, and:
found = true
}
}
}
if !found {
fmt.Println("rpm file not found")
}
如果您只需要處理 1 個.rpm文件,則不需要“狀態”管理(found變量)。如果你找到并處理了一個.rpm文件,你可以返回,如果你到達循環的結尾,你會知道沒有任何rpm文件:
for _, file := range files {
if file.Mode().IsRegular() {
if filepath.Ext(file.Name()) == ".rpm" {
// Process rpm file, and:
return
}
}
}
// We returned earlier if rpm was found, so here we know there isn't any:
fmt.Println("rpm file not found")
- 2 回答
- 0 關注
- 156 瀏覽
添加回答
舉報