登录
首页 >  Golang >  Go问答

golang 如何将 os.ModePerm 转化为字符串形式

来源:stackoverflow

时间:2024-03-10 16:06:26 414浏览 收藏

哈喽!今天心血来潮给大家带来了《golang 如何将 os.ModePerm 转化为字符串形式》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我希望将文件的权限表示形式作为 string 。 这就是我想做的:

fileInfo, err := os.Lstat(path)
fileMode := fileInfo.Mode()
// fileMode.String() gives dturwxrwxrwx or -rwxrwxrwx
// which i do not want because the size is not always the same
unixPerms := fileMode & os.ModePerm

对于这两种情况,我都得到了 -rwxrwxrwx,这与我正在寻找的很接近。

但是,返回的对象的类型为 os.filemode。然后如何将其转换为 string


解决方案


您可以将任一变量(类型为 (os.filemode))作为参数传递给 fmt 包中的 sprintf 方法。

利用此方法会将您的类型转换为字符串,然后可以在程序的其余部分中将其用作字符串。

使用示例如下:

package main

import (
    "fmt"
    "os"
)

func main() {
    fileInfo, err := os.Lstat(path)
    if err != nil {
        // catch err
    }
    fileMode := fileInfo.Mode()
    // fileMode.String() gives dturwxrwxrwx or -rwxrwxrwx
    // which i do not want because the size is not always the same
    unixPerms := fileMode & os.ModePerm

    permString := fmt.Sprintf("%v", unixPerms)
    fmt.Println(permString)
}

fileinfo.mode().perm().string()

https://golang.org/pkg/os/#FileMode.Perm

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《golang 如何将 os.ModePerm 转化为字符串形式》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>