获取“STRING”变量的 INT 值

我需要像这样的输出


0 - os.O_APPEND     - 1024

1 - os.O_CREATE     - 64

2 - os.O_EXCL       - 128

3 - os.O_RDONLY     - 0

4 - os.O_RDWR       - 2

5 - os.O_SYNC       - 1052672

6 - os.O_TRUNC      - 512

7 - os.O_WRONLY     - 1

我能做到一半


func main() {

        a := []int{os.O_APPEND,os.O_CREATE,os.O_EXCL,os.O_RDONLY,os.O_RDWR,os.O_SYNC,os.O_TRUNC,os.O_WRONLY}

        for index, value := range a {

                fmt.Printf("%d -  - %d\n", index, value)

        }

}

这给了我输出


0 -  - 1024

1 -  - 64

2 -  - 128

3 -  - 0

4 -  - 2

5 -  - 1052672

6 -  - 512

7 -  - 1

和它的另一半


func main() {

        a := []string{"os.O_APPEND","os.O_CREATE","os.O_EXCL","os.O_RDONLY","os.O_RDWR","os.O_SYNC","os.O_TRUNC","os.O_WRONLY"}

        for index, value := range a {

                fmt.Printf("%d - %-15s -\n", index, value)

        }

}

这给了我输出


0 - os.O_APPEND     -

1 - os.O_CREATE     -

2 - os.O_EXCL       -

3 - os.O_RDONLY     -

4 - os.O_RDWR       -

5 - os.O_SYNC       -

6 - os.O_TRUNC      -

7 - os.O_WRONLY     -

我怎样才能得到想要的输出?


紫衣仙女
浏览 129回答 1
1回答

繁星点点滴滴

你可以使用地图。func main() {    var m map[string]int    m = make(map[string]int)    b := []int{os.O_APPEND,os.O_CREATE,os.O_EXCL,os.O_RDONLY,os.O_RDWR,os.O_SYNC,os.O_TRUNC,os.O_WRONLY}    a := []string{"os.O_APPEND","os.O_CREATE","os.O_EXCL","os.O_RDONLY","os.O_RDWR","os.O_SYNC","os.O_TRUNC","os.O_WRONLY"}    for index, value := range a {        m[value] = b[index]    }    var i =0    for index,mapValue := range m{        fmt.Println(i," - ",index,"-",mapValue )        i++    }}输出将是:0  -  os.O_RDWR - 21  -  os.O_SYNC - 10526722  -  os.O_TRUNC - 5123  -  os.O_WRONLY - 14  -  os.O_APPEND - 10245  -  os.O_CREATE - 646  -  os.O_EXCL - 1287  -  os.O_RDONLY - 0或者你可以定义自定义结构type CustomClass struct {    StringValue string    IntValue int}func main() {    CustomArray:=[]CustomClass{        {"os.O_APPEND",os.O_APPEND},        {"os.O_CREATE",os.O_CREATE},        {"os.O_EXCL",os.O_EXCL},        {"os.O_RDONLY",os.O_RDONLY},        {"os.O_RDWR",os.O_RDWR},        {"os.O_SYNC",os.O_SYNC},        {"os.O_TRUNC",os.O_TRUNC},        {"os.O_WRONLY",os.O_WRONLY},    }    for k, v := range CustomArray {        fmt.Println(k," - ", v.StringValue," - ", v.IntValue)    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go