登录
首页 >  Golang >  Go问答

将二维切片切片转换为字符串

来源:stackoverflow

时间:2024-02-26 08:12:25 406浏览 收藏

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

问题内容

我想从数据库中获取数据并写入excel

假设我有一个类似的结构:

type user struct {
    id    int64
    name  string
    age   int
}

我可以从 db &[]user{} 中获取指向用户类型切片的指针

但我想将该切片转换为字符串 [][]string{} 的 2d 切片

这是我尝试做这样的工作的代码:

func toStrings(slice interface{}) [][]string {
    switch reflect.TypeOf(slice).Elem().Kind() {
    case reflect.Slice:
        ret := [][]string{}
        val := reflect.ValueOf(slice).Elem()
        for i := 0; i < val.Len(); i++ {

            tempSlice := []string{}

            tempV := reflect.ValueOf(val.Index(i))

            for j := 0; j < tempV.NumField(); j++ {
                tempSlice = append(tempSlice, tempV.Field(j).String())
            }

            ret = append(ret, tempSlice)
        }
        return ret
    }
    return nil

}

但是从上面的代码中我得到的是像 [<*reflect.rtype value> ] 这样的切片

我哪里做错了?

我的 golang 演示代码


解决方案


抱歉,我发现我哪里做错了,我得到了 tempv 错误

func toStrings(slice interface{}) [][]string {
    switch reflect.TypeOf(slice).Elem().Kind() {
    case reflect.Slice:
        ret := [][]string{}
        val := reflect.ValueOf(slice).Elem()
        for i := 0; i < val.Len(); i++ {

            tempSlice := []string{}

            // tempV should be:
            tempV := val.Index(i)
            // instead of reflect.ValueOf(val.Index(i))

            for j := 0; j < tempV.NumField(); j++ {
                tempSlice = append(tempSlice, tempV.Field(j).String())
            }

            ret = append(ret, tempSlice)
        }
        return ret
    }
    return nil

}

以上就是《将二维切片切片转换为字符串》的详细内容,更多关于的资料请关注golang学习网公众号!

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