登录
首页 >  Golang >  Go问答

获取“STRING”变量的 INT 值

来源:stackoverflow

时间:2024-04-10 22:42:33 429浏览 收藏

哈喽!今天心血来潮给大家带来了《获取“STRING”变量的 INT 值》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我需要像这样的输出

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     -

如何获得所需的输出?

更新

当我思考这个问题时,我想到了一个想法,用空接口数组来解决它,然后在空接口数组的每个元素上键入断言,一次使用字符串来获取字符串,然后一次用 int 来获取 int 的值,但我不知道该怎么做。


解决方案


你可以使用地图。

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++
    }
}

输出将是:

923375576​​677

或者您可以定义自定义结构

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)
    }
}

到这里,我们也就讲完了《获取“STRING”变量的 INT 值》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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