Gorm: Can I use interface{} as query destination?

Created on 19 Feb 2016  路  3Comments  路  Source: go-gorm/gorm

How should I pass interface{} containing struct? Example with x2 works, but example with x1 does not. Is it a feature or bug? Is it possible to bypass this somehow?

package extensions

type Foo struct {
    Name string
}

func list() {
    var x1 interface{} = []Foo{}
    x2 := []Foo{}

    gormDB.Find(&x1) //unsupported destination, should be slice or struct
    gormDB.Find(&x2)
}

Most helpful comment

package main

import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
)

type Foo struct {
    gorm.Model
    Name string
}

var db *gorm.DB

func find(v interface{}) {
    db.Debug().Find(v)
}

func main() {
    var err error
    db, err = gorm.Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True&loc=Local")
    if err != nil {
        panic(err)
    }

    db.AutoMigrate(&Foo{})

    var x1 = []Foo{}
    find(&x1)
}

All 3 comments

package main

import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
)

type Foo struct {
    gorm.Model
    Name string
}

var db *gorm.DB

func find(v interface{}) {
    db.Debug().Find(v)
}

func main() {
    var err error
    db, err = gorm.Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True&loc=Local")
    if err != nil {
        panic(err)
    }

    db.AutoMigrate(&Foo{})

    var x1 = []Foo{}
    find(&x1)
}

@jinzhu Hi, i don't think it will work if we assign x1 as datatype interface{}.
Is there anyway we can dynamically evaluate those variables in the query?

func main() {
    var err error
    db, err = gorm.Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True&loc=Local")
    if err != nil {
        panic(err)
    }

    db.AutoMigrate(&Foo{})

    var x1 interface{} = []Foo{}
    find(&x1)  // ERROR: unsupported destination, should be slice or struct 
}

@SherL0cked
try find(reflect.ValueOf(x1).Interface())

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rfyiamcool picture rfyiamcool  路  3Comments

Quentin-M picture Quentin-M  路  3Comments

kumarsiva07 picture kumarsiva07  路  3Comments

superwf picture superwf  路  3Comments

bramp picture bramp  路  3Comments