如何在Julia中硬编码结构变量?
我有一个Julia结构:如何在Julia中硬编码结构变量?,julia,Julia,我有一个Julia结构: struct WindChillCalc location::Tuple; w_underground_url::String; WindChillCalc(location, wug) = new(location, w_underground_url); end 在调用WindChillCalc的构造函数时,如何硬编码w_underground_url以包含“someString”?尝试以下方法 struct testStruct
struct WindChillCalc
location::Tuple;
w_underground_url::String;
WindChillCalc(location, wug) = new(location, w_underground_url);
end
在调用WindChillCalc的构造函数时,如何硬编码w_underground_url以包含“someString”?尝试以下方法
struct testStruct
x::Real
y::String
testStruct(x,y) = new(x,"printThis")
end
test = testStruct(1,"")
test2 = testStruct(2,"")
println(test.y)
println(test2.y)
它会为任何对象打印“printThis”。尝试下面的方法
struct testStruct
x::Real
y::String
testStruct(x,y) = new(x,"printThis")
end
test = testStruct(1,"")
test2 = testStruct(2,"")
println(test.y)
println(test2.y)
它为任何对象打印“printThis”。只需编写示例:
struct WindChillCalc{T}
location::T;
w_underground_url::String;
WindChillCalc(location::T) where {T <: NTuple{2, Real}} =
new{T}(location, "some string");
end
注意,我已经将参数的类型限制为两个元素的元组,其中每个元素都是Real
。当然,您可以使用另一个限制(或不使用限制)
使用这种方法,您的代码将很快,因为在编译时Julia将知道结构中所有字段的确切类型。只需编写示例:
struct WindChillCalc{T}
location::T;
w_underground_url::String;
WindChillCalc(location::T) where {T <: NTuple{2, Real}} =
new{T}(location, "some string");
end
注意,我已经将参数的类型限制为两个元素的元组,其中每个元素都是Real
。当然,您可以使用另一个限制(或不使用限制)
使用这种方法,您的代码将很快,因为在编译时Julia将知道结构中所有字段的确切类型。甚至可能
testStruct
构造函数不应使用y
位置参数,因为它没有被使用。另一件事是x
现在具有类型Real
,通常出于性能原因,您希望它是一个具体的类型(例如,可以将testStruct
参数化,从x
类型继承类型参数)。是的。。我同意你的看法。@BogumiłKamiński我很想看看只使用一个输入参数的参数化构造函数的代码是什么样子的:)我在答案中添加了一个示例。甚至可能testStruct
构造函数也不应该使用y
位置参数,因为它没有被使用。另一件事是x
现在具有类型Real
,通常出于性能原因,您希望它是一个具体的类型(例如,可以将testStruct
参数化,从x
类型继承类型参数)。是的。。我同意你的看法。@BogumiłKamiński我很想看看一个只接受一个输入参数的参数化构造函数的代码是什么样子的:)我在答案中添加了一个示例。