简体   繁体   中英

Working with interface and types on golang

I'm working on a generic implementation of a paginator for DB queries with GORM

type Cursor struct {
    Data []interface{}
    Next int
}

type Paginator struct {
    PageSize int
    Model    interface{}
}

The problem is, I don't know how to instantiate a new array to retrieve results from DB depending on the Paginator.Model type with this line

db.Model(paginator.Model).Limit(paginator.PageSize).Offset(page - 1).Find(&data)

How can I instantiate data to work with Find ?

Is your issue not knowing how to create a slice?

You can do:

var data []interface{}{} // make an empty slice of type interface{}

if you are trying to create a Custor struct, you can also do:

c := Cursor{Data: []interface{}{}}

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM