我刚刚完成了 Julia 的基本知识,为了更好地理解结构,我尝试解决一些简单的问题。
在我有自定义结构的情况下,比如 HttpRequest
,然后创建一个 HttpRequest Arrays
数组,比如 sampleArr
。
我的要求是动态更新 sampleArr[index]
中的 HttpRequest Array
。
在尝试 append!
时出现以下错误
错误:LoadError:MethodError:没有匹配长度的方法(::HttpRequest)
以下代码可以用作我正在尝试做的示例
#!/usr/bin/env julia
struct HttpRequest
httpMethod
httpHost
httpBlah
end
reqA = HttpRequest("GET", "1.1.1.1", "yada")
reqB = HttpRequest("PUT", "1.1.1.1", "blah")
reqC = HttpRequest("GET", "2.3.2.3", "boka")
reqD = HttpRequest("POST", "8.1.8.1", "juka")
reqE = HttpRequest("PUT", "4.4.4.4", "kula")
sampleArrLen = 10
sampleArr = Array{Array, 1}(undef,sampleArrLen)
sampleArr[5] = [reqA]
append!(sampleArr[5], reqB)
最佳答案
你必须使用 push!
而不是 append!
,像这样:
julia> push!(sampleArr[5], reqB)
2-element Array{HttpRequest,1}:
HttpRequest("GET", "1.1.1.1", "yada")
HttpRequest("PUT", "1.1.1.1", "blah")
julia> sampleArr
10-element Array{Array,1}:
#undef
#undef
#undef
#undef
HttpRequest[HttpRequest("GET", "1.1.1.1", "yada"), HttpRequest("PUT", "1.1.1.1", "blah")]
#undef
#undef
#undef
#undef
#undef
push!
和 append!
的区别在于 push!
将单个元素推送到集合中并 append!
将某个其他集合的所有元素附加到集合的末尾。因此,下面的代码可以工作 append!(sampleArr[5], [reqB])
并给出与 push!(sampleArr[5], reqB)
相同的结果。这里的区别在于您将 reqB
包装在一个数组中,因此现在您将单个元素集合附加到 sampleArr
。
关于julia - 附加!自定义类型混合时失败并显示 "no method matching length",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57230598/