Go language Assignment

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The value of a variable can be updated using an assignment statement, and the simplest assignment statement is to place the variable that will be assigned to the left of =, and the new value's expression to the right of =.

1                       // 命名变量的赋值true                   // 通过指针间接赋值"bob"         // 结构体字段赋值// 数组、slice或map的元素赋值

The compound operation for a particular two-tuple arithmetic operator and an assignment statement has a concise form, such as the last statement above can be rewritten as:

count[x] *= scale

This saves you from repeating the calculation of the variable expression.

Numeric variables can also support ++ increment and -- decrement statements, which are statements, not expressions, so x = i++ that expressions are wrong:

1 v++    // 等价方式 v = v + 1;v 变成 2v--    // 等价方式 v = v - 1;v 变成 1

Tuple assignment

A tuple assignment is another form of an assignment statement that allows the value of multiple variables to be updated at the same time. Before assigning a value, all expressions to the right of the assignment statement are evaluated first, and then the value of the corresponding variable on the left is updated uniformly. This is useful for dealing with variables that appear both on the left and right side of the tuple assignment statement, for example, we can exchange the values of two variables:

x, y = y, x a[i], a[j] = a[j], a[i]
例子求最大公约数:
//计算两个整数的最大公约数intint { for0 { x, y = y, x%y } return x }

Example Fibonacci sequence (Fibonacci):

//计算斐波纳契数列(Fibonacci)的第N个数intint { x, y :01    for0; i < n; i++ { x, y = y, x+y } return x }

Tuple assignments can also make a series of trivial assignments more compact:

235

However, if the expression is too complex, you should try to avoid excessive use of tuple assignments, because each variable assignment statement is more readable.

Some expressions produce multiple values, such as calling a function that has multiple return values. When such a function is called in the expression to the right of the tuple assignment, the number of the left variable must be the same as the right.

f, err = os.Open("foo.txt"// function call returns two values

Typically, such functions use an additional return value to express some type of error, such as the OS. Open uses an extra return value to return an error of an error type, and some is used to return a Boolean value, often called OK. The three operations we will see later are similar usages. If a map lookup, type assertion, or channel receive appears to the right of an assignment statement, they may produce two results, and an additional Boolean result indicates whether the operation was successful:

v, ok = m[key]             // map lookupv, ok = x.(T)              // type assertionv, ok = <-ch               // channel receive

Note: When a map lookup, type assertion, or channel receive appears to the right of an assignment statement, it does not necessarily produce two results, or it may produce only one result. For cases where the value produces a result, the map lookup fails with a value of 0, a runtime panic exception is sent when the type assertion fails, and a 0 value is returned when the channel receives failure (blocking is not considered a failure). For example, the following example:

v = m[key]                // map查找,失败时返回零值v = x.(T)                 // type断言,失败时panic异常v = <-ch                  // 管道接收,失败时返回零值(阻塞不算是失败) _, ok = m[key]            // map返回2个值_, ok = mm[""false     // map返回1个值_ = mm[""]                // map返回1个值

As with variable declarations, we can _ discard unwanted values with an underscore blank identifier.

// 丢弃字节数_, ok = x.(T)              // 只检测类型,忽略具体值

can be assignable

An assignment statement is an explicit assignment, but there are many places in the program where implicit assignment behavior occurs: The function call implicitly assigns the value of the calling parameter to the parameter variable of the function, and a return statement implicitly assigns the value of the return operation to the result variable, and the literal of a composite type produces the assignment behavior. For example, the following statement:

medals := []string{"gold""silver""bronze"}

Each element of the slice is implicitly assigned operations, similar to the behavior of this write:

medals[0"gold" medals[1"silver" medals[2"bronze"

The elements of map and Chan, although not ordinary variables, have similar implicit assignment behavior.

Whether implicitly or explicitly assigned, the variable on the left of the assignment statement and the final value on the right must have the same data type. To be more straightforward, only the value on the right is assignable to the left variable, and the assignment statement is allowed.

The assignable rules have different requirements for different types, and we will specifically explain each new type of special place. For the types we have discussed, its rules are simple: types must match exactly, nil can be assigned to any pointer or reference type variable. Constants have more flexible assignment rules, because this avoids unnecessary explicit type conversions.

Can be used for two values = = or ! = The ability to perform equality comparisons is also related to the ability to assign values: for equality comparisons of values of any type, the second value must be a variable that corresponds to the first value type, and vice versa.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.