Golang — Extract value from interfaces{} without specifying the Struct Type

Let say you pass struct as an interface argument to function and you do not have access to the type struct then how to extract the fields values.

Now you are trying to figure out why the heck i need to do this, lol. But there are many cases where you do not have access to the TYPE.

Let’s take an example i am building a go pkg and i want user to specify there own Table Struct but on my pkg i want to access the values of that struct which i do not have access to directly.

Live Example: https://play.golang.org/p/73OH5zYxjAF


package main
import (
type User struct {
 UserEmail string
 UserPass  string
func login(user interface{}) {
 ////--- Extract Value without specifying Type
 val := reflect.ValueOf(user).Elem()
 n := val.FieldByName("UserEmail").Interface().(string)
 fmt.Printf("%+v\n", n)
func main() {
 login(&User{UserEmail: "lucian@knesk.com", UserPass: "lucian123"})



Our practice is built around your needs

Let us take the weight of product development off your shoulders and boost your digital presence.