朱莉娅:将元素追加到自定义类型的数组中 [英] Julia: Append an element to an array of custom types

查看:71
本文介绍了朱莉娅:将元素追加到自定义类型的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Julia中将元素添加到数组的工作原理如下:

Appending an element to an array in Julia works like this:

v = Array{Int32, 1}(0)
append!(v, 1)
append!(v, 2)
println(v)  # prints: Int32[1,2]

当我尝试使用自定义类型

When I try this with a custom type

type Node
    label::String
    value::Int32
end
nodes = Array{Node, 1}(0)
append!(nodes, Node("a", 42))

我收到以下错误:

ERROR: LoadError: MethodError: no method matching length(::Node)

我假设我必须实现" length方法,但是不知道如何.

I assume I have to 'implement' the length method but do not know how.

推荐答案

append!命令不会执行您认为的操作.您正在考虑push!命令.

The append! command doesn't do what you think it does. You're thinking of the push! command.

append!命令附加到两个数组中.这两个参数都必须是数组:

The append! command appends two arrays together. Both arguments need to be arrays:

julia> append!(nodes, [Node("a", 42)])
1-element Array{Node,1}:
 Node("a",42)

length实施必要的
(该错误只是告诉您它试图读取第二个参数的数组长度,发现不是数组的东西.)

No length implementing necessary
(that error was just telling you it tried to read the length of your array for the second argument and found something that was not an array.)

这篇关于朱莉娅:将元素追加到自定义类型的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆