Getting Started with Go language basics-variables, types

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

1. Variables

the variable declaration of the Go language differs from the C + + language. The go language introduces the var keyword. The variable declarations are as follows:
var v1 int//declares an integer variable V1var v2 stringvar v3 [10]int//array var v4 []int//Array tile var v5 struct {//struct  F int}var V6 *int//pointer var V7 map[string] Int//map,ley to String,value for Intvar V8 func (a int) int
as you can see, the declaration of a variable is not semicolon-terminated. The var keyword can also define multiple variables at once:
var (  v1 int   v2 string)
Initialization of variables
var v1 int = 10//correct usage 1var v2 = 10//correct use mode 2, the compiler can automatically deduce the type of v2 v3: = 10//correct use of 3, the compiler can automatically deduce the type of V3
use: = can reduce the amount of code written, which is a great benefit to programmers but in the course of our use, it should not appear as follows:
var i inti: = 2<span style= "font-family: ' Microsoft Yahei ';" >//Wrong practices </span>
assigning values to variables
var v10 int//first declared, then assigned v10 = 123i, j = 2, 3//go supports multiple assignments
we can easily exchange two-digit values by multiple assignments .
I, j = j, the i//compiler calculates the value to the right of the equal sign, and then assigns the value to the left
Anonymous Variables
The Go language supports multiple return values and anonymous variables
Func GetName (FirstName, LastName, nickname string) {return "may", "Chan", "Chibi Maruko"}
returns the FirstName, LastName, nickname, which are all three variables of type string When we receive the parameters returned by the function, we can also choose to accept the sex, use _ to ignore the parameters
_, _, Nickname: = GetName ()
Constants in the Go language, constants refer to values that are known and immutable during compilation. Constants can be numeric types (including integer, float, and complex types), Boolean types, string types, and so on.
The following is a literal constant-123.14159265358979323846//constant of the floating-point type 3.2+12i///complex Type constant TRUE//Boolean type constant "foo"//String constant
Definition of Constants
Const Pi float64 = 3.14159265358979323846const zero = 0.0//non-type floating-point constant const (size int64 = 1024x768 EOF =-1//untyped integer constant) const U, V float32 = 0, 3//U = 0.0, v = 3.0, constant multi-assignment const A, b, C = 3, 4, "foo"//a = 3, B = 4, c = "foo", untyped integer and string constant
If a constant is defined without a qualified type, then the constant is a literal constant. The right-hand value of a constant definition can also be a constant expression that is evaluated at compile time, such as:
Const MASK = 1 << 3
because the assignment of a constant is a compile-time behavior, an rvalue cannot have any expression that requires a run time to produce a result, such as attempting to define a constant in such a way as to cause a compilation error:
Const HOME = os. GETENV ("HOME")
pre-defined constants The Go language pre-defines these constants: True, False, and iota.
Iota is special and can be thought of as a constant that can be modified by the compiler, which is reset to 0 when each const keyword appears, and then, before the next const appears, each time a iota is present, the number it represents is automatically increased by 1.
The following example can be used to understand the usage of iota basically:
Const (  //iota reset to 0C0 = iota//C0 = = 0C1 = Iota//C1 = 1C2 = Iota//c2 = = 2) const (A = 1 << iota//A = = 1 (Iota at each const start is reset to 0) b = 1 << iota//b = = 2c = 1 << iota//c = = 4) const (U = Iota *//U = 0v float64 = Iota *//V = = 42.0w = Iota */w = = +) Const X = iota//x = = 0 (because iota is reset to 0) const Y = iota//y = = 0 (ibid. )
If the expression of the two Const assignment statement is the same, then the latter assignment expression can be omitted. Therefore, the first two const statements above can be abbreviated as:
Const (///iota is reset to 0c0 = iota//C0 = 0C1//C1 = 1C2//c2 = 2) const (A = 1 <<iota//A = = 1 (iota is reset at each const start) is 0) b/b = = 2c//c = = 4)

Enumeration

Enumeration refers to a series of related constants, such as the following about the daily definition of one weeks. Using the example in the previous section, we see that you can define a set of constants in the form of a const followed by a pair of parentheses, which is commonly used in the go language to define enumeration values. The go language does not support enum keywords that are explicitly supported in many other languages.
Const (Sunday = iotamondaytuesdaywednesdaythursdayfridaysaturdaynumberofdays//This constant is not exported)
As with other symbols in the go language, start with capital lettersThe constants are visible outside the package. In the example above, Numberofdays is private in the package and other symbols can be accessed by other packages.


Type

The Go language contains the following basic types:
Boolean type: BOOL.
Integral type: int8, Byte, int16, int, uint, uintptr, etc.
Floating-point types: float32, float64.
Plural type: complex64, complex128.
String: String.
Character type: Rune.
Fault type: Error.
In addition, the go language supports the following composite types:
Pointer (pointer)
Arrays (Array)
Slicing (slice)
Dictionary (map)
Channel (Chan)
struct (struct)
Interface (interface)
above these underlying types go also encapsulates the following types: int, uint, uintptr, and so on. These types are characterized by ease of use, but the user cannot make any assumptions about the length of these types. For conventional development, it is possible to use int and uint, and there is no need to explicitly specify length types such as int8 to avoid porting difficulties.
BOOL Type the Boolean type in the Go language is basically the same as other languages, and the keyword is bool, which can be assigned a predefined true and false example code as follows:
var v1 boolv1 = Truev2: = (1 = = 2)//V2 will also be deduced as bool type
Boolean types cannot accept other types of assignments, and automatic or forced type conversions are not supported. The following example is an incorrect usage that causes a compilation error:
var b boolb = 1//Compile error B = bool (1)//Compile error The following usage is correct: var b boolb = (1!=0)//compile the correct FMT. PRINTLN ("Result:", b)//print result is result:true
Integral type

1. Type representation
It should be noted that int and int32 are considered to be two different types in the go language, and the compiler will not help you do the type conversion automatically, such as the following example will have a compilation error:
var value2 int32value1: =//value1 will be automatically deduced as int type value2 = value1//Compile Error
This compilation error can be resolved with coercion type conversion:
Value2 = Int32 (value1)//compile through
Of course, developers need to be aware of the loss of data accuracy (such as forcing floating-point numbers to integers) and value overruns (when the value exceeds the range of values of the target type of the conversion) when the data length is truncated, while forcing type conversions.

2. Numerical operations
The Go language supports the following general integer operations: +,-, *,/, and%. Subtraction is not explained in detail, it is necessary to say that% and in C language is the same as the remainder of the operation, such as:
5% 3//Result: 2

3. Comparison operations The Go language supports several comparison operators: >, <, = =, >=, <=, and! =. This is the same as most other languages and is exactly the same as the C language.
The following is an example of a conditional judgment statement:
I, J: = 1, 2if i = = J {fmt. Println ("I and J are equal.")}
Two different types of integers cannot be directly compared, such as the number of int8 types and the number of int cannot be directly compared, but all types of integer variables can be directly compared with literal constants (literal), such as:
var i int32var j int64i, j = 1, 2if i = = J {  //Compilation error FMT. Println ("I and J are equal.")} if i = = 1 | | j = = 2 {//compile via FMT. Println ("I and J are equal.")}

4. Bit arithmetic

most of the bit operators in the go language are similar to the C language, except that they are ~x in the C language and ^x in the go language.

floating point type
Float is used to represent data that contains a decimal point, for example, 1.234 is a floating-point data. Floating-point types in the go language are represented by the IEEE-754 standard.
1. Floating-point numbers indicate
The go language defines two types float32 and float64, where float32 is equivalent to the float type of C,
The float64 is equivalent to the double type of the C language.
In the go language, the code that defines a floating-point variable is as follows:
var fvalue1 float32fvalue1 = 12fvalue2: = 12.0//If you do not add a decimal point, fvalue2 is deduced as an integer instead of a floating-point type
For the fvalue2 that the type is automatically deduced in the example above, it is important to note that its type is automatically set to float64, regardless of whether the number assigned to it is represented by a 32-bit length. Therefore, for the above example, the following assignment will cause the compilation
Error:
Fvalue1 = Fvalue2
Instead, you must use such coercion type conversions:
fvalue1 = float32 (fvalue2)
2. Floating-point comparison
Because floating-point numbers are not an exact representation, it is not feasible to use = = as an integer to determine whether two floating-point numbers are equal, which can lead to unstable results.
The following is a recommended alternative:
Import "math"//p for user-defined comparison accuracy, such as 0.00001func isequal (F1, F2, p float64) bool {return math. Fdim (F1, F2) < P}
plural type
The complex number is actually composed of two real numbers (represented by floating-point numbers in the computer), one representing the real part (real), and one representing the imaginary part (IMAG). The plural of the go language is easy to understand if you know what the math complex is all about.
1. Plural representation
Examples of plural representations are as follows:
var value1 complex64//complex type consisting of 2 float32 value1 = 3.2 + 12ivalue2: = 3.2 + 12i//value2 is complex128 type value3: = Complex (3. 2)  //VALUE3 results with  value2
2. Real and imaginary parts
For a complex z = complex (x, y), the real (z) of the complex can be obtained through the go language built-in function real
Part, that is, X, obtains the imaginary part of the complex number by imag (z), that is, Y.
For more functions on complex numbers, consult the documentation for the MATH/CMPLX standard library.
string
In the go language, strings are also a basic type. In contrast, there is no native string type in the C + + language, usually represented by a character array and passed as a character pointer.
The Declaration and initialization of strings in the go language is simple, for example:
var str string//Declare a string variable str = "Hello World"//String Assignment ch: = str[0]//Take the first character of the string fmt. Printf ("The length of \"%s\ "is%d \ n", str, Len (str)) FMT. Printf ("the first character of \"%s\ "is%c.\n", str, CH)
The output is:
The length of ' Hello World ' is 11The first character of ' Hello World ' is H.
The contents of a string can be obtained in a manner similar to an array subscript, but unlike an array, the contents of the string cannot be modified after initialization, such as the following example:
str: = "Hello World"//string also supports the practice of initializing when declaring str[0] = ' X '//Compile Error
In this example we use a go language built-in function Len () to take the length of the string. This function is very useful and is often used when working with strings, arrays, and slices in the actual development process.
In this section we also demonstrate the use of the printf () function. Readers with the C language base will find that the printf () function is used in the same ways as the printf () function in the C language runtime. When readers learn more about the Go language later, they can use println () and printf () to print a variety of information that they are interested in, making the learning process more intuitive and interesting.
The go compiler supports UTF-8 source code file format. This means that the strings in the source code can contain non-ANSI characters, such as "Hello world." Hello, world! "Can appear in the Go code. But it's important to note that if your go generation
Code needs to contain non-ANSI characters, please note that the encoding format must be selected UTF-8 when saving the source file. In particular, under Windows, the General editor is default to local encoding, such as the Chinese region may be GBK encoding instead of UTF-8, if not aware of this, there will be some unexpected situations when compiling and running.
Encoding conversion of strings is a very common requirement for working with text documents such as TXT, XML, HTML, and so on, but unfortunately the go language only supports UTF-8 and Unicode encoding. For other encodings, the Go Language standard library does not have built-in encoding conversion support. Fortunately, however, we can easily package one with CGO based on the Iconv library. Here is an open source project:
Https://github.com/xushiwei/go-iconv.

1. String manipulation

for more string operations, refer to the standard library strings package.

2. String traversal
The go language supports two ways of traversing a string. One is traversing in a byte array:
str: = "Hello, world" N: = Len (str) for I: = 0; I < n; i++ {ch: = Str[i]//based on the subscript to the character in the string, the type is byte FMT. Println (i, CH)}
The output of this example is:
0 721 1012 1083 1084 1115 446 327 2288 1849 15010 23111 14912 140
As you can see, this string length is 13. Although intuitively, this string should be only 9 characters. This is because each Chinese character occupies 3 bytes in UTF-8, not 1 bytes.
The other is to traverse with Unicode characters:
str: = "Hello, world" For I, ch: = Range str {FMT. Println (i, CH)//ch is of type Rune}
The output is:
0 721 1012 1083 1084 1115 446 327 1999010 30028
When traversing in Unicode characters, the type of each character is Rune (the earlier Go language uses the int type to represent Unicode
character), rather than byte. Character type
two character types are supported in the go language, one is a byte (actually an alias of Uint8), a single byte value representing the UTF-8 string, and the other is a rune, substituting a single Unicode character.
For rune related operations, refer to the Unicode package of the Go standard library. In addition, the Unicode/utf8 package also provides conversion between UTF8 and Unicode. For the sake of simplifying the language, most APIs in the go language assume that the string is UTF-8 encoded. Although Unicode characters are supported in the standard library, they are actually less used.
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.