Go Language Core Beauty 1.3-assignment and type declaration

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

Assign Value (Assignment)

The value of the variable can be updated with the assignment operator = v = 10.

x = 1                       //named variable x*p = True                   //pointer variable person.name = "Bob"/         /field of struct struct count[x] = count[x] * Scale//array, slice or map Elements

Both the arithmetic operator and the bitwise operator have a corresponding unary operator, and V = v + x is equivalent to V + = x, for example:
COUNT[X] *= Scale
This kind of thumbnail can save a lot of repetitive work, while the number variable can also increment or decrement by + +:
V: = 1v++    //Same as V = v + 1, v becomes 2v--    //Same as V = V-1; v becomes 1 again

1. Tuple (tuple) assignment Tuple assignment allows assigning values to multiple variables at once. = The expression on the right is evaluated before the variable on the left is updated, which is useful when the same variable is present on both sides, such as swapping the values of two variables:
X, y = y, xa[i], a[j] = A[j], a[i]
Another example is the calculation of the two-digit greatest common divisor (GCD):
Func gcd (x, y int) int {for Y! =    0 {        x, y = y, x%y    }    return x}
Or calculate the nth value of the Fibonacci sequence:
Func fib (n int) int {    x, y: = 0, 1 for    I: = 0; i < n; i++ {        x, y = y, x+y    }    return x}

Tuple assignments can also combine some scattered assignments:
I, j, K = 2, 3, 5

But if the expression is more complex, you should try to avoid the tuple assignment, and the readability of the assigned value is better.

Some specific expressions, such as a function call, have multiple return values, in which case = The left must have a corresponding number of variables to assign the value:

F, err = OS. Open ("Foo.txt")  //function call has two return values

Many times, the function takes advantage of this multiple return value attribute to return an extra value that indicates whether the function's call was successful (either an error type variable err, or a bool type variable OK). Finding a value in map, type assertion, receiving a value from a channel, and so on will have two return values, where the second value is a bool type:

V, OK = m[key]             //Map LOOKUPV, OK = x. (T)              //Type Assertionv, OK = <-ch               //channel receive

The go language also supports anonymous variables (which readers of the functional language should be aware of), and we can assign unwanted values to blank identifiers (= the number of variables on the left and the number of values on the right must be the same):

_, err = Io. Copy (DST, SRC)//Only care about the success of copy, do not care about the number of bytes of the specific copy, so discard the first value _, OK = x. (T)              //Only care about the success of type assertion, do not care about the specific value of x, so discard the first value

2. can be assigned value

the above assignment statement is an explicit assignment, but in some cases an implicit assignment occurs: implicitly assigned to a function argument in a function call, when the function returns, implicitly assigns the operand to return, and a combination type similar to the following:

Medals: = []string{"Gold", "Silver", "bronze"}
Here is the implicit assignment, which is the equivalent of the explicit form:
Medals[0] = "Gold" medals[1] = "Silver" medals[2] = "Bronze"

The same is true for maps, channel types, and so on, all of which support this implicit assignment.

Whether it is an explicit assignment or an implicit assignment, only the right and left sides have the same type.

Specific assignment rules for different types are explained in detail in subsequent chapters. For the types we have discussed, the rules are simple: types must match exactly (so go is a strongly typed static language) and nil can be assigned to interface or other reference types. Constant (constant) assignment is very flexible in type conversions, which avoids most explicit type conversions:

Const x = 112var v float64 = x  fmt. Println (v)//output:112
Whether two variables can be compared with = = or! = depends on the assignable value, a = = B can only be judged if a = B is feasible.

Type declaration

The type of the variable defines some of the personalization properties of the variable, such as the amount of memory the variable occupies, the arrangement in memory, the organization of the variable, the operation supported by the variable, the behavior method of the variable, and so on.

In a real project, many custom types have the same underlying type, for example: int can be a circular index, a timestamp, a file descriptor, or a month; the float64 type can be a vehicle speed, temperature. You can declare a named type by using the type, which allows you to build your own type of timestamp, file descriptor, and so on above the underlying type.

Type name Underlying-type
namedType declarations generally take place at the package level, so the type is visible within packages, and if the type is exported (capitalized), it is globally visible. To interpret the type declaration, the different units of temperature measurement are set to different types:
Package Tempconvimport "FMT" type Celsius float64type Fahrenheit float64const (    absolutezeroc Celsius = -273.15    FREEZINGC     Celsius = 0    boilingc      Celsius = +) func ctof (c Celsius) Fahrenheit {return Fahrenheit (C*9/5 + 32)} Func FToC (f Fahrenheit) Celsius {return Celsius ((f-32) * 5/9)}
aboveTwo types of Celsius (degrees Celsius) and Fahrenheit (Fahrenheit) are defined as two different units of temperature. Even though the underlying types of the two types are the same float64, but they are completely different types, they cannot be compared with each other and cannot be combined in an arithmetic expression, which avoids the erroneous use of two different units of temperature, since the types of two temperature units are different, The two values returned by Ctof and Ftoc are also completely different.



For each type of T, there is a corresponding type conversion t (x), which converts the X to the T type. Type conversions can be performed when and only if two types have the same underlying type, such as Celsius and Fahrenheit above, or two types are pointer types and point to the same underlying type.

Conversions can be made between numeric types, between string and []byte, which may alter the representation of a value. For example, converting a floating-point number to an integer will intercept the small tree part; Converting a string into a []byte slice allocates memory space to create a copy of a string (memory copy is often one of the performance bottlenecks). In short, the type conversion is the completion of the compilation period, in the run time will not fail!

The underlying type of a named type determines its structure and representation, and it also determines the basic operations it supports (which can be understood as inheriting from the underlying type), as if it were directly using the underlying type. Therefore, for Celsius and Fahrenheit, float64 supports arithmetic operations that support:

Fmt. Printf ("%g\n", BOILINGC-FREEZINGC)//"100" °CBOILINGF: = Ctof (BOILINGC) fmt. Printf ("%g\n", Boilingf-ctof (FREEZINGC))//"180" °ffmt.printf ("%g\n", BOILINGF-FREEZINGC)       //Compile Error:type Mismatch
Another example:
Type temp IntFunc main () {var x1 temp = 1var x2 temp = 2fmt. PRINTLN (x1 + x2)//output:3}

if two values have the same named type, you can compare them with the comparison operator = = and <, or two values, one for the named type, one for the underlying type of the named type, or for comparison. However, two different named types can not be directly compared:

var c Celsiusvar F fahrenheitfmt.println (c = = 0)          //"true" FMT. Println (f >= 0)          //"true" FMT. Println (c = = f)          //Compile Error:type mismatchfmt. Println (c = = Celsius (f))//"true"!

We all know that floating-point numbers are imprecise expressions, so the comparison between two floating-point numbers requires extra care. Note here that the comparison between floating-point numbers after the last type conversion, Celsius (f) does not change the value of F, because both C and F two are initialized to 0, so you can be assured of comparisons.


Using named variables can be a great convenience if you need to repeat a complex type in some areas of your project.


We can also define specific behaviors for named types, which are type methods in the Go language, which we'll explain in more detail in subsequent chapters.

The following code defines a methond:string for the Celsuis type,

Func (c Celsius) string () string {return FMT. Sprintf ("%g°c", C)}

Many custom types define a string method because when a function of the FMT package is called to print the type, string controls how that type is printed (this is actually the interface that implements the stringer, and unlike other OO languages, the interface implementation of the go Language is implicit):
c: = FToC (212.0) fmt. Println (c.string ())//"100°c" FMT. Printf ("%v\n", c)   //"100°c"; no need to call String explicitlyfmt. Printf ("%s\n", c)   //"100°c" FMT. Println (c)          //"100°c" FMT. Printf ("%g\n", c)   //"+"; does not-call Stringfmt.println (Float64 (c))//"+"; does not-call String



Welcome to join the Go language core technology QQ group 894864, inside a lot of enthusiastic God Oh!

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.