在朱莉娅中的一个类型内的数组

exs*_*ake 3 arrays types julia

我正在尝试使用内部数组制作一个类型,但却无法做到.

这是我的代码:

type Gradient
    color::GrandientPoint
    Gradient(color=[]) = new(color)
    function Gradient(rgb::RGB)
        push!(color,GrandientPoint(rgb,0))
    end
end
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误

错误:UndefVarError:颜色未定义

我究竟做错了什么?

Chr*_*kas 8

function Gradient(rgb::RGB)
    push!(color,GrandientPoint(rgb,0))
end
Run Code Online (Sandbox Code Playgroud)

你从来没有在color这里做过,所以你不能push!进入,color因为它不存在.实际上,你不需要.要定义类型,只需new使用它的值调用:

function Gradient(rgb::RGB)
    new(GrandientPoint(rgb,0))
end
Run Code Online (Sandbox Code Playgroud)

这使得Gradient第一个字段获取值的位置GrandientPoint(rgb,0),并返回它.


如果你想要一个数组,那么你的类型就是

type Gradient
    color::Vector{GrandientPoint}
end
Run Code Online (Sandbox Code Playgroud)

不只是GraidentPoint.现在,您可以使用其构造函数创建该向量.类型具有类型名称的合理构造函数.所以要做一个Vector{GrandientPoint},你就是这样做的

Vector{GraidentPoint}()
Run Code Online (Sandbox Code Playgroud)

你可以把东西推进那里.构造函数的完整代码:

type Gradient
    color::Vector{GrandientPoint}
    Gradient(color=[]) = new(Vector{GradientPoint}())
    function Gradient(rgb::RGB)
        color = Vector{GradientPoint}()
        push!(color,GrandientPoint(rgb,0))
        new(color)
    end
end
Run Code Online (Sandbox Code Playgroud)