代码之家  ›  专栏  ›  技术社区  ›  rnso

为什么此处无法识别此变量

  •  0
  • rnso  · 技术社区  · 4 年前

    我正在努力学习朱莉娅。为什么以下简单代码没有运行:

    chnum = 3
    while chnum < 100
        println(chnum)
        chnum = chnum + 2
    end 
    

    错误是:

    RROR: LoadError: UndefVarError: chnum not defined        <<<<< NOTE THIS.
    Stacktrace:
     [1] top-level scope at /home/iuser/testing.jl:4 [inlined]
     [2] top-level scope at ./none:0
     [3] include at ./boot.jl:317 [inlined]
     [4] include_relative(::Module, ::String) at ./loading.jl:1044
     [5] include(::Module, ::String) at ./sysimg.jl:29
     [6] exec_options(::Base.JLOptions) at ./client.jl:266
     [7] _start() at ./client.jl:425
    in expression starting at /home/iuser/testing.jl:3
    

    为什么是 chnum 此处无法识别变量?

    0 回复  |  直到 4 年前
        1
  •  1
  •   ahnlabb    4 年前

    这是因为Julia中的范围界定是如何工作的。文档中有一个非常好的页面 Scope of Variables ,特别相关的是该部分 On Soft Scope 这解释了为什么规则是这样的,并提供了一些历史(行为随着时间的推移而有所变化,在Julia 1.5中,你的代码可以在REPL或笔记本电脑中工作)。

    在这种情况下,声明:

    chnum = 3
    

    声明一个名为的全局变量 chnum .当 while 循环开始时,由于没有名为的局部变量,因此创建了一个新的局部(软)作用域 chnum 它没有被定义。

    可以通过声明来防止错误 chnum global :

    chnum = 3
    while chnum < 100
        global chnum
        println(chnum)
        chnum = chnum + 2
    end
    

    或者通过将整个事物包装在引入局部作用域的构造中:

    function print_stuff()
        chnum = 3
        while chnum < 100
            println(chnum)
            chnum = chnum + 2
        end
    end
    print_stuff()
    
    推荐文章