#Help with interface and generics

12 messages · Page 1 of 1 (latest)

slender flame
#

Hi, new gopher here.

type DBModel interface {
  Test() //sample
}


type Product struct {}
func (p Product) Test() {} //sample

type Person struct {}
func (p Person) Test() {} //sample

type Pagination interface {
  GetRows() []*T //i want this to allow Product and/or Person
}

type ProductPagination struct {
  Rows []*Product
}

type PersonPagination struct {
  Rows []*Person
}

func (pagination ProductPagination) GetRows() []*Product {
  return pagination.Rows
}

func (pagination PersonPagination) GetRows() []*Person{
  return pagination.Rows
}

func Foo(pagination Pagination) {
  t := pagination.GetRows() //not working
}

Question: is there an easier/simpler way for Foo to accept any struct that implements Pagination?
Note that in my sample above, the GetRows is not correct since idk yet how declare the type

spring zealot
#

GetRows should be part of the interface requirements

#

Let's say some other struct implements pagination, but doesn't have a GetRows function?

slender flame
#

GetRows should be part of the interface requirements
you mean this?

type Pagination interface {
  GetRows() []*T //i want this to allow Product and/or Person
}
#

GetRows can be removed (which is better for me), but interface in golang cant have fields right? only methods

#

ideally

type Pagination interface {
  Rows []*T
}

but as far as i learned in golang, interface cant have fields in interface

spring zealot
#

I don't think you can use interfaces to what you're trying to do
Could you clarify more on your intentions?

slender flame
#

i want a function Foo that can accept any pagination struct. In that function i want to access the struct's Rows type, can be a []*Product or []*Person and so on

#

something like

func Foo(pagination Pagination) {
  for i := range pagination.Rows {
  }
}
spring zealot
#

But it's a different type everytime, how are you going to process it in the same way?

#

The row

slender flame
#

Yeah those are structs implementing the DBModel interface