这是我在 Julia 中寻找的伪代码实现:
struct Example
field1::Float64
field2::Float64
end # End struct
example = Example(1., 2.)
function modifystruct(mystruct, fieldname)
mystruct.fieldname +=10
return mystruct
end
modifystruct(example, field1)
# In this instance I would want to have example.field1 = 11.
Run Code Online (Sandbox Code Playgroud)
我实际上该怎么做?我想提供类似字符串的字段名,并让我的 struct."whateverfieldname" 得到这样的修改。我应该补充一点,我不想编写这样的代码:
function modifystruct(mystruct, fieldname)
if fieldname = "fieldname1"
mystruct.field1 +=10
end
if fieldname = "fieldname2"
mystruct.field2 +=10
end
return mystruct
end
Run Code Online (Sandbox Code Playgroud)
很大程度上是因为我希望这段代码具有多用途性。我的程序可能使用不同类型的结构,因此我可以通过字段名称直接访问的结构越接近越好。有没有任何方法或实现可以为我做到这一点?
当然,那就是setproperty!(value, name, x)和getproperty(value, name):
function modifystruct(mystruct, fieldname)
new_field = getproperty(mystruct, fieldname) + 10
setproperty!(mystruct, fieldname, new_field)
return mystruct
end
Run Code Online (Sandbox Code Playgroud)
正如 DecowVR 正确指出的那样,这需要mystruct是可变的。
如果您想使用嵌套属性重复执行此操作,您可能会对Setfield.jl提供的镜头感兴趣。