julia - 附加!自定义类型混合时失败并显示 "no method matching length"

标签 julia

我刚刚完成了 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/

相关文章:

julia - 如何将一些数据附加到 Julia 中的文件?

julia - 错误:BoundsError:尝试访问索引为[0]的1元素数组{SubString {String},1}

file - 写入文件? Julia 语言

julia - 在 Julia 1.0+ : How do I get strings using redirect_stdout

julia - Julia 中的特征分解和 "composition"

julia - 为什么十六进制或二进制数的类型是 Uint64 而十进制数的类型是 Int64?

python - Julia 符号和数字性能对比 Python

arrays - Julia,将 2d 数组合并到 3d 数组上?

jupyter-notebook - 无法在 jupyter lab 上运行 julia 1.7.3 内核

hashmap - 是否有允许搜索一系列键的 julia 结构?