golang中如何获取文件的扩展名?

golang中如何获取文件的扩展名?

在go的path包里,有func Ext(path string) string方法,这个方法可以获取文件的扩展名,他的返回值是带点.的,比如文件名称是test.txt, 使用这个函数后,返回值是.txt。如果文件没有扩展名,这个方法返回空字符。详情查看源码。

// Ext returns the file name extension used by path.
// The extension is the suffix beginning at the final dot
// in the final slash-separated element of path;
// it is empty if there is no dot.
func Ext(path string) string {
	for i := len(path) - 1; i >= 0 && path[i] != '/'; i-- {
		if path[i] == '.' {
			return path[i:]
		}
	}
	return ""
}

从源码中可以看出,是从字符串的最后一个字符开始遍历,遇到点.结束。如果没有扩展名,则遇到/就结束。最差的情况是把整个字符串都遍历一边。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值