2 回答
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
試試這個(gè)
...
splitted := strings.Split(file.Name(), ".")
lenSplit := len(splitted)
if lenSplit > 1 && splitted[lenSplit-1] == "rpm" {
// file with extension
}
...
用“.”分割文件名
轉(zhuǎn)到字符串?dāng)?shù)組中的最后一個(gè)字符串
檢查最后一個(gè)字符串是否匹配“rpm”
TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
.rpm在任何一次迭代中都無法判斷是否沒有文件具有擴(kuò)展名。您只能在檢查所有文件后才能確定。
因此,與其嘗試將其壓縮到循環(huán)中,不如維護(hù)一個(gè)found變量,您可以在.rpm找到文件時(shí)對(duì)其進(jìn)行更新。
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 個(gè).rpm文件,則不需要“狀態(tài)”管理(found變量)。如果你找到并處理了一個(gè).rpm文件,你可以返回,如果你到達(dá)循環(huán)的結(jié)尾,你會(huì)知道沒有任何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 關(guān)注
- 174 瀏覽
添加回答
舉報(bào)
