23

在某些编程语言中,我看到(例如):

x := y

这个:=操作符一般叫什么,它有什么作用?

4

7 回答 7

27

在所有支持运算符的语言中,:=这意味着赋值。

  • 在支持运算符:=的语言中,=运算符通常表示相等比较。
  • =意味着赋值的语言中,==通常用于相等比较。

是什么:=意思=

我不记得任何与 .:=含义相同的语言=


在 MySQL中:==两者都用于赋值,但是它们不可互换,选择正确的取决于上下文。为了使事情更加混乱,=运算符也用于比较。赋值或比较的解释=也取决于上下文。

于 2012-05-01T23:40:47.410 回答
11

这是 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

于 2019-05-03T14:03:21.920 回答
8

我通常在伪代码中更多地看到它,这意味着分配。因此 x := y 表示“将 x 的值设置为 y 的值”,而 x = y 表示“x 的值是否等于 y 的值?”

于 2012-05-01T23:40:47.663 回答
3

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)

于 2019-04-28T21:50:33.540 回答
1

许多语言使用通用运算符。通常,它=是为变量赋值保留的,如果它是单独的,则不应在数学上下文中查看。尽管测试了 Java 和 Bash 等某些语言中的平等性==

于 2012-05-02T14:11:26.543 回答
1

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;)。

于 2012-05-02T20:09:15.140 回答
0

:= 意思是“设置等于”一个有语法的赋值

v := expr 将变量 «v» 的值设置为从表达式 «expr» 获得的值。

示例: X := B 将 X 的定义设置为 B 的值

于 2022-02-12T04:39:22.897 回答