我有以下代码
using Plots
function test()::nothing
A::Array{Float64,1} = rand(Float64,100)
plot(A)
end
Run Code Online (Sandbox Code Playgroud)
我像这样在朱莉娅中运行
julia> include("main.jl")
test (generic function with 1 method)
julia> test()
ERROR: MethodError: First argument to `convert` must be a Type, got nothing
Stacktrace:
[1] test() at /path/to/main.jl:85
[2] top-level scope at REPL[2]:1
Run Code Online (Sandbox Code Playgroud)
为什么我会收到错误消息First argument to convert must be a Type, got nothing?
nothing好吧,这个问题与您在注释中使用的事实有关,但正确的类型是Nothing(注意大写N)。nothing是一个对象,Nothing是这个对象的类型。
所以你应该使用类似的东西
function test()::Nothing
A::Array{Float64,1} = rand(Float64, 100)
display(plot(A))
nothing
end
Run Code Online (Sandbox Code Playgroud)
请注意,我必须添加nothing作为返回值并显式地display显示实际绘图。
但说实话,主要问题不是专业化Nothing,而是过度专业化。函数中的类型注释不会加快计算速度,您应该仅在真正需要时使用它们,例如在多重调度中。
惯用的代码看起来像这样
function test()
A = rand(100)
plot(A)
end
Run Code Online (Sandbox Code Playgroud)
请注意,我删除了Float64中的所有额外注释和不必要的注释rand,因为它是默认值。
| 归档时间: |
|
| 查看次数: |
727 次 |
| 最近记录: |