翻译进度
4
分块数量
1
参与人数

Assignments

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。


Assignment = ExpressionList assign_op ExpressionList .
assign_op = [ add_op | mul_op ] "=" .

每个左操作数必须为可寻址值、一个 map 索引表达式或(仅对于 = 赋值)空白标识符 。操作数可以用括号括起来。

x = 1
*p = f()
a[i] = 23
(k) = 

赋值操作 x op= y (op 是二进制 算数运算符)等同于 x = x op (y)但是仅对 x估值一次。 op= 构造整体是一个操作符。在赋值操作中,左表达式列表和右表达式列表都必须只有一个单值表达式,并且左表达式不能为空白标识符。

singee 翻译于 4年前
a[i] 

元组赋值将多值操作的各个元素分配给变量列表。有两种形式。首先,右侧操作数是单个多值表达式,例如函数调用、通道map操作或类型断言。左侧的操作数数量必须与值的数量匹配。例如,如果f是一个返回两个值的函数,

x, y = f()

将第一个值分配给x,将第二个值分配给y

在第二种形式中,左侧的操作数必须等于右侧的表达式的数量,每个表达式都必须是单值,并且右侧的第 n 个表达式被分配给左边的第 n个操作数:

one, two, three = '一', '二', '三'
singee 翻译于 4年前

The blank identifier provides a way to ignore right-hand side values in an assignment:

_ = x       // evaluate x but ignore it
x, _ = f()  // evaluate f() but ignore second result value

The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.

a, b = b, a  // exchange a and b

x := []int{1, 2, 3}
i := 0
i, x[i] = 1, 2  // set i = 1, x[0] = 2

i = 0
x[i], i = 2, 1  // set x[0] = 2, i = 1

x[0], x[0] = 1, 2  // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end)

x[1], x[3] = 4, 5  // set x[1] = 4, then panic setting x[3] = 5.

type Point struct { x, y int }
var p *Point
x[2], p.x = 6, 7  // set x[2] = 6, then panic setting p.x = 7

i = 2
x = []int{3, 5, 7}
for i, x[i] = range x {  // set i, x[2] = 0, x[0]
    break
}
// after this loop, i == 0 and x == []int{3, 5, 3}

In assignments, each value must be assignable to the type of the operand to which it is assigned, with the following special cases:

  1. Any typed value may be assigned to the blank identifier.
  2. If an untyped constant is assigned to a variable of interface type or the blank identifier, the constant is first implicitly converted to its default type.
  3. If an untyped boolean value is assigned to a variable of interface type or the blank identifier, it is first implicitly converted to type bool.

本文章首发在 LearnKu.com 网站上。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

贡献者:1
讨论数量: 0
发起讨论 只看当前版本


暂无话题~