这行代码在Julia编程语言中的意思是什么?

huangapple go评论71阅读模式
英文:

What does this line of code mean in Julia Programming Language

问题

function commence(args::Vector{String})
这一行的意思是,定义一个名为"commence"的函数,该函数接受一个名为"args"的参数,参数的类型限定为Vector{String},即一个存储字符串的向量。

英文:
function commence(args::Vector{String})

What I would like to know is, what does this line mean? Particularly, what does the argument of commence, "(args::Vector{String})" mean?

答案1

得分: 4

这行代码指示了一个名为commence的函数的定义,它接受一个名为args的单一参数。::Vector{String}部分指定只有字符串向量,也就是类型为Vector{String}的对象,才会被该函数接受。请参考以下演示:

julia> function commence(args::Vector{String})
           @show args
           nothing
       end
commence (generic function with 1 method)

julia> commence([1,2,3])
ERROR: MethodError: no method matching commence(::Array{Int64,1})
Closest candidates are:
  commence(::Array{String,1}) at REPL[1]:2
Stacktrace:
 [1] top-level scope at REPL[2]:1

julia> commence("asd","test")
ERROR: MethodError: no method matching commence(::String, ::String)
Stacktrace:
 [1] top-level scope at REPL[3]:1

julia> commence(["asd","test"]) # 正常工作,因为args的类型是Vector{String}
args = ["asd", "test"]

我建议你阅读手册,特别是这部分,以了解更多关于Julia中函数的信息。

英文:

The line indicates the definition of a function named commence which takes a single argument args. The ::Vector{String} bit specifies that only vectors of strings, i.e. objects of type Vector{String}, will be accepted by the function. See the following demonstration:

julia> function commence(args::Vector{String})
           @show args
           nothing
       end
commence (generic function with 1 method)

julia> commence([1,2,3])
ERROR: MethodError: no method matching commence(::Array{Int64,1})
Closest candidates are:
  commence(::Array{String,1}) at REPL[1]:2
Stacktrace:
 [1] top-level scope at REPL[2]:1

julia> commence("asd","test")
ERROR: MethodError: no method matching commence(::String, ::String)
Stacktrace:
 [1] top-level scope at REPL[3]:1

julia> commence(["asd","test"]) # works, since typeof(args) == Vector{String}
args = ["asd", "test"]

I recommend you read through the manual, in particular this part, to learn more about functions in Julia.

答案2

得分: 0

:: 表示强制类型,类似于 typeassert()。
还可参考 https://docs.julialang.org/en/v1/base/punctuation/ [Julia 标点][1]

英文:

:: means enforce the type similar to typeassert().
Also see https://docs.julialang.org/en/v1/base/punctuation/ [Julia Puntuation][1]

huangapple
  • 本文由 发表于 2020年1月6日 23:53:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定