Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access struct values inside an interface

I have an interface{} that is similar like -

Rows interface{}

In the Rows interface i put ProductResponse struct.

type ProductResponse struct {
    CompanyName     string                        `json:"company_name"`
    CompanyID       uint                          `json:"company_id"`
    CompanyProducts []*Products                   `json:"CompanyProducts"`
}
type Products struct {
    Product_ID          uint      `json:"id"`
    Product_Name        string    `json:"product_name"`
}

I want to access Product_Name value. How to access this. I can access outside values (CompanyName , CompanyID) by using "reflect" pkg.

value := reflect.ValueOf(response)
CompanyName := value.FieldByName("CompanyName").Interface().(string)

I am not able to access Products struct values. How to do that?

like image 863
Md. Abu Farhad Avatar asked Apr 25 '26 04:04

Md. Abu Farhad


2 Answers

You can use type assertion:

pr := rows.(ProductResponse)
fmt.Println(pr.CompanyProducts[0].Product_ID)
fmt.Println(pr.CompanyProducts[0].Product_Name)

Or you can use the reflect package:

rv := reflect.ValueOf(rows)

// get the value of the CompanyProducts field
v := rv.FieldByName("CompanyProducts")
// that value is a slice, so use .Index(N) to get the Nth element in that slice
v = v.Index(0)
// the elements are of type *Product so use .Elem() to dereference the pointer and get the struct value
v = v.Elem()

fmt.Println(v.FieldByName("Product_ID").Interface())
fmt.Println(v.FieldByName("Product_Name").Interface())

https://play.golang.org/p/RAcCwj843nM

like image 193
mkopriva Avatar answered Apr 27 '26 06:04

mkopriva


Instead of using reflection you should use type assertion.

res, ok := response.(ProductResponse) 
if ok { // Successful
   res.CompanyProducts[0].Product_Name // Access Product_Name or Product_ID
} else {
   // Handle type assertion failure 
}
like image 38
cod3rboy Avatar answered Apr 27 '26 07:04

cod3rboy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!