📜  在 Julia 中为命名字段设置值 – setfield() 方法

📅  最后修改于: 2022-05-13 01:55:16.654000             🧑  作者: Mango

在 Julia 中为命名字段设置值 – setfield() 方法

setfield()是 julia 中的一个内置函数,用于将值x分配给复合类型值中的命名字段。该值必须是可变的,并且 x 必须是 fieldtype(typeof(value), name) 的子类型

句法:

setfield(value, name::Symbol, x)

参数:

  • value:复合类型的指定值。
  • name::Symbol:指定的符号。
  • ×:规定值。

返回:它将分配的值x返回到复合类型值中的命名字段。示例 1:

Python
# Julia program to illustrate
# the use of setfield() method
  
# Getting the assigned value 'x' to
# a named field in value of composite type.
mutable struct MyMutableStruct
           field::Int
       end
 
a = MyMutableStruct(1);
setfield (a, :field, 123);
println(getfield(a, :field))


Python
# Julia program to illustrate
# the use of setfield() method
  
# Getting the assigned value 'x' to
# a named field in value of composite type.
a = 5//3
println(setfield (a, :num, 123))


输出:

123

示例 2:

Python

# Julia program to illustrate
# the use of setfield() method
  
# Getting the assigned value 'x' to
# a named field in value of composite type.
a = 5//3
println(setfield (a, :num, 123))

输出:

ERROR: LoadError: type Rational is immutable
while loading /home/cg/root/5090533/main.jl, in expression starting on line 7