Julia :關於函數返回類型::

julia> function y()::Int64
          return 5
       end
y (generic function with 1 method)

表明y()返回的是Int64. 假定改一下,如下:

julia> function y() ::String
          return 5
       end
y (generic function with 1 method)

julia> y()
ERROR: MethodError: Cannot `convert` an object of type Int64 to an object of type String
Closest candidates are:
  convert(::Type{
   
   String}, ::CategoricalArrays.CategoricalValue) at C:\Users\songroom\.julia\packages\CategoricalArrays\0ZAbp\src\value.jl:60
  convert(::Type{
   
   T}, ::T) where T<:AbstractString at strings/basic.jl:229
  convert(::Type{
   
   T}, ::AbstractString) where T<:AbstractString at strings/basic.jl:230
  ...
Stacktrace:
 [1] y() at .\REPL[8]:2
 [2] top-level scope at REPL[9]:1
julia> function y() ::Float64
          return 5
       end
y (generic function with 1 method)

julia> y()
5.0

但對以下的類型,。

julia> function x(a)
          if a< 5
             return 6
          else
                return "a"
          end
       end
x (generic function with 1 method)

julia> x(4)
6

julia> x(7)
"a"

有二種方法:比如,Any或Union{}

julia> function x(a) ::Any
          if a< 5
             return 6
          else
             return "a"
          end
       end
x (generic function with 1 method)

julia> x(4)
6

julia> x(7)
"a"

julia> function x(a) ::Union{
   
   Int64,String}
          if a< 5
             return 6
          else
             return "a"
          end
       end
x (generic function with 1 method)

julia> x(4)
6

julia> x(7)
"a"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章