Dynamic field in struct

Hey Guys,
I wanna make a product struct that contains some key-value depends on every product for example for a mobile we have this property: “screen-size”: “5” and … and for another product like a pot: “deep”: 4 and … I must make property in my struct that has JSON type and save it into database this field as JSON?
and what about permissions for users? I must do the same?

more explain:
I wanna make e-commerce. that we have some product here that admins can add into the database and customers can see and buy. every product has some property side of the name of product and price of product and … we have a field that is property contains dynamic value per every product for example for mobile we have some property (key-value) base and for a pot in the kitchen, we have some other property (again key-value base). now how I must implement this. for example, I know the name of product has a string type in product struct. and price has float type but this property must have what type in go and Postgres DB

2 Likes

Isn’t the best solution here to use Map?

  • A map is an unordered collection of key-values pairs.
  • Maps are used to retrieve, update or remove a value by its associated key.
  • In Go, a map , is a reference to a hash table, where all the keys are distinct.
  • Map type is written map[K]V where K and V are types of its keys and values.
  • A map has a length and a capacity, which are modifiable.
  • Maps are Go’s built-in associative data type

I have written a full article on Map maybe it can be useful.
I’m still learning GO at full throttle but I’m not sure this is the most suitable option for your task. From what I can read of your description this seems the perfect deal for what you are looking for.

Cheers.

3 Likes

Thank you. If I wanna Implement array of map structure on struct it will look like this: Property []map[string]string json:"property".
and how I must fill it in API and save it into Postgres db and again read it from Postgres?
as I said we have different key and different value

2 Likes

Hi, @mehrdaddolatkhah, Maybe this article will help you: https://www.alexedwards.net/blog/using-postgresql-jsonb

3 Likes

Sorry for not commenting on the rest, but don’t do that.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.