博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mgo 批量插入--具体类型的切片 转 interface 切片解决办法
阅读量:2397 次
发布时间:2019-05-10

本文共 1083 字,大约阅读时间需要 3 分钟。

通过xml.Unmarshal获得一个[]Province 然后想把它插到mongodb中,使用的是mgo driver。 那么怎样将[]Province切片转为[]interface{}切片呢?

法1.

c := session.DB(database).C("Provinces") var provinces []Province var docs []interface{}  ... for _,v := range provinces{    docs = append(docs,v) } c.Insert(docs...)

法2.

package mainimport (    "fmt"    "reflect")type a struct {    CreateTime int    Name       string    Content    string}func main() {    arr1 := []a{        a{Name: "no1", CreateTime: 1, Content: "hello1"},        a{Name: "no2", CreateTime: 2, Content: "hello2"},        a{Name: "no3", CreateTime: 3, Content: "hello3"},        a{Name: "no4", CreateTime: 4, Content: "hello3"},    }    fmt.Println(arr1)    arr2 := ToInterfaceArr(arr1)    fmt.Printf("%T\n", arr2)    fmt.Println(arr2)}func ToInterfaceArr(arr interface{}) []interface{} {    if reflect.TypeOf(arr).Kind() != reflect.Slice {        return nil    }    arrValue := reflect.ValueOf(arr)    retArr := make([]interface{}, arrValue.Len())    for k := 0; k < arrValue.Len(); k++ {        retArr[k] = arrValue.Index(k).Interface()    }    return retArr}

 

转载地址:http://zofob.baihongyu.com/

你可能感兴趣的文章
maven入门
查看>>
一次归档报错的处理和分析
查看>>
Python实现的快速排序
查看>>
自动化平台中的ORM和权限设计
查看>>
初识Neo4j
查看>>
Bootstrap相关项目推荐
查看>>
去中央台参加节目是怎样一种体验
查看>>
自动化平台开发小结(四)
查看>>
如何提高餐厅点菜效率的思考
查看>>
《硅谷钢铁侠》读书分享(一)
查看>>
web脚本编辑器ACE Editor
查看>>
恭贺新春-杨建荣敬祝
查看>>
使用Echarts来实现数据可视化
查看>>
过年前的计划
查看>>
关于自动化平台的动态菜单设计(二)
查看>>
恭王府游记
查看>>
Django Celery初识
查看>>
中国科技馆之行
查看>>
《唐人街探案2》观后感
查看>>
Python基础之os和数据结构
查看>>