const不那么const

打开新的REPL
image

不能忽略waning啊

文档说的很清楚了

help?> const
search: const isconst MathConstants codeunits ncodeunits countlines count_ones count_zeros checkbounds

const

const is used to declare global variables whose values will not change. In almost all code (and particularly performance sensitive code) global variables should be declared constant in this way.

const x = 5

Multiple variables can be declared within a single const:

const y, z = 7, 11

Note that const only applies to one = operation, therefore const x = y = 1 declares x to be constant but not y. On the other hand, const x = const y = 1 declares both x and y constant.

Note that "constant-ness" does not extend into mutable containers; only the association between a variable and its value is constant. If x is an array or dictionary (for example) you can still modify, add, or
remove elements.

In some cases changing the value of a const variable gives a warning instead of an error. However, this can produce unpredictable behavior or corrupt the state of your program, and so should be avoided. This
feature is intended only for convenience during interactive use.

const原则上不能再次修改,只不过REPL会丢警告出来。

至于为什么说它会produce unpredictable behavior or corrupt the state of your program呢?举个最简单的例子:

julia> const C=42
42

julia> f()=C
f (generic function with 1 method)

julia> @code_native f()
	.section	__TEXT,__text,regular,pure_instructions
; ┌ @ REPL[2]:1 within `f'
	movl	$42, %eax
	retq
	nopw	%cs:(%rax,%rax)
; └

julia> const C=100
WARNING: redefining constant C
100

julia> f()
42

因为C是常量,因此生成的f代码里的C被替换成了立即数42,后续你对C做的修改不会对已编译的f产生影响。
Julia虽然可以交互式使用,但也是有编译步骤的,并没有那么动态化。

注意,这里调用code_native宏的时候会触发代码生成,就好像你手动调用了f一样。

1赞

京ICP备17009874号-2