Dynamically accessing a field from a struct

Published on Nov 29, 2016

Say you have a struct for a blog post:

> post = %Post{title: "hello world"}

And you want to access the properties of the Post struct dynamically using an atom. You probably first tried this:

> post = %Post{title: "hello world"}
> field_name = :title
> post[field_name]
** (UndefinedFunctionError) function Post.fetch/2 is undefined (Post does not implement the Access behaviour)

You shouldn’t be surprised that you got that error.

But don’t worry, you CAN actually access the fields of a struct dynamically. A struct after all is implemented using a map.

The solution is to use Map.get/2

> post = %Post{title: "hello world"}
> field_name = :title      
> Map.get(post, field_name)
"hello world"