K
K
KirSupi2022-03-23 16:31:38
go
KirSupi, 2022-03-23 16:31:38

What is the correct way to store different types in one structure field?

There are User, Subscriber and Admin structures

type Admin struct {
  Permissions map[string]interface{}
}
type Subscriber struct {
  Online        bool
  Status        string
  SubscriptedTo []int
}
type User struct {
  ID    int
  Login string
  Role  string // "subscriber"/"admin"
  RoleModel ??? // здесь должен быть Admin{} или Subscriber{}
}

How is it more correct to write the Admin or Subscriber structure in User.RoleModel depending on the role? If you do it through an empty interface, then you constantly need to run it through mapstructure.Decode
Maybe there are some ideas how to solve a similar task differently?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
uvelichitel, 2022-03-23
@KirSupi

I think you're upside down... Maybe so?

type Admin struct {
  Permissions map[string]interface{}
  User
}
type Subscriber struct {
  Online        bool
  Status        string
  SubscriptedTo []int
  User
}
type User struct {
  ID    int
  Login string
}

M
Micro Null, 2022-03-24
@micronull

You can use typed constants to enumerate a type.

const (
  NewUserType  userType = "NEW"
  AdminType  userType = "ADMIN"
)

type User struct {
  ID    int
  Login string
  Type userType
}

Although this is not suitable for a specific case. Here it is better to use RBAC.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question