我想在 Julia 中锁定一个变量的类型,怎么办?比如我定义了一个叫做weight的数组,
weight = Array{Float64,1}([1,2,3])
现在我想把权重的类型锁定为Array{Float64,1},可以吗?
我的意思是如果不锁定重量的类型,那么如果我错误地或随意地做了
weight = 1
那么weight就会变成一个Int64变量,所以就不再是一维数组了。这显然不是我想要的。
我只想确保一旦我将权重定义为一维 Float64 数组,那么如果我更改权重类型,我希望 Julia 给我一个错误,指出权重类型已更改,这是不允许的。是否有可能?谢谢!
这很有用,因为这样做可以防止我忘记权重是一维数组,从而防止错误。
答案 0 :(得分:3)
对于 global
变量使用 const
:
julia> const weight = Array{Float64,1}([1,2,3])
3-element Vector{Float64}:
1.0
2.0
3.0
julia> weight[1]=11
11
julia> weight=99
ERROR: invalid redefinition of constant weight
请注意,重新定义引用会引发警告:
julia> const u = 5
5
julia> u=11
WARNING: redefinition of constant u. This may fail, cause incorrect answers, or produce other errors
您可以使用 Ref
类型绕过它:
julia> const z = Ref{Int}(5)
Base.RefValue{Int64}(5)
julia> z[] = 11
11
julia> z[] = "hello"
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Int64
在函数中使用 local
和类型声明:
julia> function f()
local a::Int
a="hello"
end;
julia> f()
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Int64
答案 1 :(得分:2)
你通常会写:
weight::Vector{Float64} = Array{Float64,1}([1,2,3])
...但这在全球范围内似乎是不可能的:
julia> weight::Vector{Float64} = Array{Float64,1}([1,2,3])
ERROR: syntax: type declarations on global variables are not yet supported
Stacktrace:
[1] top-level scope
@ REPL[8]:1
但是,您可以在本地范围内或在 struct
中执行此操作:
julia> function fun()
weight::Vector{Float64} = Array{Float64,1}([1,2,3])
weight = 1
end
fun (generic function with 1 method)
julia> fun()
ERROR: MethodError: Cannot `convert` an object of type Int64 to an object of type Vector{Float64}
Closest candidates are:
convert(::Type{T}, ::AbstractArray) where T<:Array at array.jl:532
convert(::Type{T}, ::LinearAlgebra.Factorization) where T<:AbstractArray at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.6/LinearAlgebra/src/factorization.jl:58
convert(::Type{T}, ::T) where T<:AbstractArray at abstractarray.jl:14
...
Stacktrace:
[1] fun()
@ Main ./REPL[10]:3
[2] top-level scope
@ REPL[11]:1
您可以使用 const
,但是使用相同类型的值重新定义会导致警告:
julia> const weight = Array{Float64,1}([1,2,3]);
julia> weight = [2.]
WARNING: redefinition of constant weight. This may fail, cause incorrect answers, or produce other errors.
1-element Vector{Float64}:
2.0