Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Julia中硬编码结构变量?_Julia - Fatal编程技术网

如何在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

我有一个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
           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我很想看看一个只接受一个输入参数的参数化构造函数的代码是什么样子的:)我在答案中添加了一个示例。