Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Using type assertion to cast entry in map to type

I am trying to cast the type of an entry in the context map to a certain type:

// r is type = r *http.Request

user := context.Get(r,"logged_in_user");

if user == nil {
    panic("no logged in user.");
}

if _, ok := user.(person.Model); !ok {
    panic("user is not a person model.")
}

role := user.Role;  // ERROR 

if role == "" {
    panic("no logged in user.");
}

but I get this error:

Unresolved reference Role

Is there a better way to code this section, so that I cast the entry in the map to a type?

I also tried this:

   user, ok := context.Get(r,"logged_in_user").(person.Model);

    if ok == false {
        panic("'logged_in_user' is not in the context map.")
    }

    if user == nil {   // ERROR
        panic("no logged in user.");
    }

but then I get this error:

Cannot convert nil to type person.Model

Comments