# Should we avoid assignment of derived types in robust programs?

**URL:** <https://fortran-lang.discourse.group/t/should-we-avoid-assignment-of-derived-types-in-robust-programs/2359>\
**Category:** Uncategorized\
**Created:** [December 2, 2021, 8:59am UTC](https://fortran-lang.discourse.group/t/should-we-avoid-assignment-of-derived-types-in-robust-programs/2359 "2021-12-02T08:59:37Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![ivanpribec](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/ivanpribec/32/3290_2.png) [@ivanpribec](https://fortran-lang.discourse.group/u/ivanpribec)\
**Post date:** [December 6, 2021, 3:23pm UTC](https://fortran-lang.discourse.group/t/should-we-avoid-assignment-of-derived-types-in-robust-programs/2359/8 "2021-12-06T15:23:28Z")

</div>

One possible way of getting a non-assignable object while using a form of RAII, is to use _associate_.

First you need to overload the structure constructor:

```fortran
  function new_ext_t(val) result(this)
    integer, intent(in), optional :: val
    type(ext_t) :: this

    if (present(val)) then
      this%val = val
    end if
  end function

```

Next you build a facade module that only exposes the overloaded structure constructor, but keeps the type hidden:

```fortran
module test_facade
  use test, only: ext_t => new_ext_t
end module

```

Finally, you instruct consumers to use the container within an associate block:

```fortran
program testprog
  use test_facade, only: ext_t
  implicit none

  type(ext_t) :: a ! compile-time error

  associate(ext => ext_t(3))
    ! ... access public members of ext ...
    ext = ext_t(4) ! compile-time error
  end associate

```

Inside the associate statement I believe you can still call any type-bound methods (not sure what happens if a method is `intent(out)`). The objects is also supposed to be finalized upon exiting the associate block (see [Should associate trigger automatic finalization?](https://fortran-lang.discourse.group/t/should-associate-trigger-automatic-finalization/2324)). Unfortunately, you may bump into issues with compiler support.

Their is a nice example of this pattern in the [nlopt-f](https://github.com/grimme-lab/nlopt-f) library for defining callbacks that get passed to a calling C routine.

Edit: If you need a copy, you can overload the structure constructor with a second method,

```fortran
module test_facade

  use test, only: new_ext_t, copy_ext_t
  private

  public :: ext_t

  interface ext_t
    procedure :: new_ext_t, copy_ext_t
  end interface

end module

```

that can be used with a second associate statement:

```auto
  associate(this => ext_t(3))
    ! ...
    associate(copy => ext_t(this))
      ! ...
    end associate
  end associate

```

---

_[View the full topic](https://fortran-lang.discourse.group/t/should-we-avoid-assignment-of-derived-types-in-robust-programs/2359)._
