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