在某些编程语言中,我看到(例如):
x := y
这个:=
操作符一般叫什么,它有什么作用?
在某些编程语言中,我看到(例如):
x := y
这个:=
操作符一般叫什么,它有什么作用?
这是 Python 3.8 中的一个新运算符,实际上在 BDFL Guido van Rossum 的提前退休中发挥了作用。
形式上,运算符允许所谓的“赋值表达式”。非正式地,算子被称为“海象算子”。
它允许在评估表达式的同时进行赋值。
所以这:
env_base = os.environ.get("PYTHONUSERBASE", None)
if env_base:
return env_base
可以缩短为:
if env_base := os.environ.get("PYTHONUSERBASE", None):
return env_base
https://www.python.org/dev/peps/pep-0572/#examples-from-the-python-standard-library
我通常在伪代码中更多地看到它,这意味着分配。因此 x := y 表示“将 x 的值设置为 y 的值”,而 x = y 表示“x 的值是否等于 y 的值?”
The symbol is called "becomes" and was introduced with IAL (later called Algol 58) and Algol 60. It is the symbol for assigning a value to a variable. One reads x := y;
as "x becomes y".
Using ":=" rather than "=" for assignment is mathematical fastidiousness; to such a viewpoint, "x = x + 1" is nonsensical. Other contemporary languages might have used a left arrow for assignment, but that was not common (as a single character) in many character sets.
Algol 68 further distinguished identification and assignment; INT the answer = 42;
says that "the answer" is declared identically equal to 42 (i.e., is a constant value). In INT the answer := 42;
"the answer" is declared as a variable and is initially assigned the value 42.
There are other assigning symbols, like +:=
, pronounced plus-and-becomes; x +:= y
adds y to the current value of x, storing the result in x.
(Spaces have no significance, so can be inserted "into" identifiers rather than having to mess with underscores)
许多语言使用通用运算符。通常,它=
是为变量赋值保留的,如果它是单独的,则不应在数学上下文中查看。尽管测试了 Java 和 Bash 等某些语言中的平等性==
PL/I 有(有?)=
和:=
。=
用于赋值和比较——编译器试图根据上下文找出你的意思。当/如果它决定在你真正意味着分配的地方进行比较,你可以使用:=
强制分配。
例如,考虑x=y=0;
在 C 中(例如),这意味着“将 0 分配给 y,然后将结果(也是 0)分配给 x”。
在 PL/I 中,这意味着将 y 与 0 进行比较,然后将该比较的布尔结果分配给 x(即,相当于x = y == 0;
在 C 中)。如果你(理智,不像 PL/I 的设计者)想要表示“将 0 分配给 x 和 y”,你会使用x = y := 0;
(或x := y := 0;
)。
:= 意思是“设置等于”一个有语法的赋值
v := expr 将变量 «v» 的值设置为从表达式 «expr» 获得的值。
示例: X := B 将 X 的定义设置为 B 的值