<commit_before>---
published: true
title: .__struct__/1 is undefined, cannot expand struct
layout: post
categories: [elixir]
---
Trying to create something like constructor, but using struct within the same model does not work :(

```elixir
defmodule App.News.Event.NewItemAdded do
  defstruct id: nil, title: nil, contents: nil, featuredImageId: nil, gallery: nil

  alias App.News.Command.AddNewsItem

  def make(id, command = %AddNewsItem{}), do:
    %NewItemAdded{
      id: id,
      title: command.title,
      contents: command.contents,
      featuredImageId: command.featuredImageId,
      gallery: command.gallery}
end
```
Code will produce compile error:
`(CompileError) web/domain/news/events/new_item_added.ex:7: NewItemAdded.__struct__/1 is undefined, cannot expand struct NewItemAdded`

But [ExConstructor](https://github.com/appcues/exconstructor) somehow managed to make it work. A little bit of digging into source code and i found `__MODULE__`. So i changed make function to fallowing and now it works :)

```elixir
  def make(id, command = %AddNewsItem{}), do:
    %__MODULE__{
      id: id,
      title: command.title,<commit_msg>Post update: .__struct__/1 is undefined, cannot expand struct<commit_after>---
published: true
title: .__struct__/1 is undefined, cannot expand struct
layout: post
categories: [elixir]
---
Trying to create something like constructor, but using struct within the same model does not work :(

```elixir
defmodule App.News.Event.NewItemAdded do
  defstruct id: nil, title: nil, contents: nil, featuredImageId: nil, gallery: nil

  alias App.News.Command.AddNewsItem

  def make(id, command = %AddNewsItem{}), do:
    %NewItemAdded{
      id: id,
      title: command.title,
      contents: command.contents,
      featuredImageId: command.featuredImageId,
      gallery: command.gallery}
end
```
Code will produce compile error:

`(CompileError) web/domain/news/events/new_item_added.ex:7: NewItemAdded.__struct__/1 is undefined, cannot expand struct NewItemAdded`

But [ExConstructor](https://github.com/appcues/exconstructor) somehow managed to make it work. A little bit of digging into source code and i found `__MODULE__`. So i changed make function to fallowing and now it works :)

```elixir
  def make(id, command = %AddNewsItem{}), do:
    %__MODULE__{
      id: id,
      title: command.title,
{'fraction_non_alphanumeric': 0.10123351765206295, 'fraction_numerical': 0.0029774564015312634, 'mean_word_length': 4.19205298013245, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3754202', 'n_tokens_mistral': 708, 'n_tokens_neox': 693, 'n_words': 251}