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 关注
- 169 浏览
添加回答
举报