Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Access a struct's properties through an interface{}

Tags:

struct

go

I am having trouble in accessing the one struct's properties (named Params) in different file.

please consider x.go where i invoke a function(CreateTodo)

type Params struct {
    Title  string `json:"title"`
    IsCompleted int `json:is_completed`
    Status  string `json:status`
}

var data = &Params{Title:"booking hotel", IsCompleted :0,Status:"not started"}

isCreated := todoModel.CreateTodo(data) // assume todoModel is imported

now CreateTodo is a method on a struct (named Todo) in different file lets say y.go

type Todo struct {
    Id  int `json:todo_id`
    Title  string `json:"title"`
    IsCompleted int `json:is_completed`
    Status  string `json:status`
}

func (mytodo Todo)CreateTodo(data interface{}) bool{
    // want to access the properties of data here
    fmt.Println(data.Title) 
    return true
}

Now I just want to use properties of data in CreateTodo function in y.go. But i am not able to do so and getting following error

data.Title undefined (type interface {} is interface with no methods)

I am sure issue is around accepting struct as an empty interface but i am not able to figure out.

Please help here.Thanks

like image 276
Siyaram Malav Avatar asked Jun 17 '26 00:06

Siyaram Malav


1 Answers

So you have one of two options, depending on your model:

#1

Switch to data *Params instead of data interface{} as suggested in another answer but it looks like you are expecting different types in this function, if so; check option #2 below.

#2

Use Type switches as follows:

func (t Todo) CreateTodo(data interface{}) bool {
    switch x := data.(type) {
    case Params:
        fmt.Println(x.Title)
        return true

    // Other expected types

    default:
        // Unexpected type
        return false
    }
}

P.S. Be careful with your json tags: it should be json:"tagName". Notice the ""! Check go vet.

like image 146
ifnotak Avatar answered Jun 20 '26 10:06

ifnotak