Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can I use interface{} as query destination? #857

Closed
hypertornado opened this issue Feb 19, 2016 · 3 comments
Closed

Can I use interface{} as query destination? #857

hypertornado opened this issue Feb 19, 2016 · 3 comments

Comments

@hypertornado
Copy link

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)
}
@jinzhu
Copy link
Member

jinzhu commented Feb 21, 2016

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 jinzhu closed this as completed Feb 21, 2016
@SherL0cked
Copy link

SherL0cked commented Jul 23, 2019

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

@Yanght115
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants