Is there a way to call the field of a derived type using a string?

StackOverflow https://stackoverflow.com/questions/23071709

  •  03-07-2023
  •  | 
  •  

سؤال

Is there a way to call the field of a derived type via string argument in fortran?

something like...

subroutine set(car, fieldName, value)
    type(Car_T) :: car
    character*(*) :: fieldName
    character*(*) :: value

    car%[fieldName] = value
end subroutine set

I know you can do stuff like this in javascript, c#, ect., but this could really help me from having a ton of duplicate code if fortran allows it.

هل كانت مفيدة؟

المحلول 2

You can do something similar with namelists but it is for items known to the program: not new items.

integer:: inin
real:: rere
namelist /info/ inin, rere

inin = 0 ! default
rere = 20.4 ! default
read (*, nml=info)
print *, 'inin=', inin
print *, 'rere=', rere

stop
end

On the input

&info inin=2 rere=40.0 /

Or if you wish to input one value only

&info rere=3.162 /

نصائح أخرى

No. You will need to write the executable code (perhaps a SELECT CASE construct) that maps the value of the string across to the relevant component.

You only need to write this once for each unique set of component names.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top