Go start: 3, variables, constants, and underlying types

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

Prior to this, the development environment of Go was built and the basic structure of Go program was understood. A Go development tool has been selected. With these, you can now continue to explore the charm of go.

Variable

Declaration, initialization

In go, the declaration of a variable uses the keyword var, which is the same as javascript,pascal. Var is also used to define variables in swift, and it seems that new languages tend to use special keywords to declare variables. However, the format of the variable declaration and JavaScript is still very different, to some like Pascal and swift– are type information placed after the variable name , the difference is not to use: Split.

varint          //定义类型为int的变量v1varstring       //定义类型为string的变量v2

It can also be seen that a variable declaration statement does not need to use a semicolon as a terminator. Many languages now discard semicolons at the end of the statement, like Python,swift,r and so on. This does not know what the trend is.
Go as a relatively new language, in some of the wording there are some relatively special practices. Another usage like the var keyword is that you can put several variables that need to be declared together.
For example, like above, it is also stated that V1 and V2 can write:

var(          int          string )

The var keyword can be omitted even if the variable declaration can be initialized directly.

varint100//  var100    // 编译器可以自动推导出v2的类型 100       // 编译器可以自动推导出v3的类型 


As can be seen here, the first way to give a warning, the mouse is placed on the alert message is "should omit type int from declaration of VAR v1; It'll be inferred from the right-hand side ". It means that the type of Var V1 should be omitted as int; it will be inferred from the right. You can see that the specified type is no longer required, and go can infer the variable type from the right value of the initialization expression, which makes go look a bit like a dynamic type language such as JavaScript, but go is actually a Java-like static type language.
The third type introduces a ": =" symbol. This is where the var keyword can be omitted during initialization of the variable. This symbol should be the original of go. It is important to note that each statement outside the function must start with a keyword (Var, func, and so on), so: = struct cannot be used outside of the function.
The above three ways are supported by go, the specific use of which can choose their own.

Assign value

In go syntax, variable initialization and variable assignment are two different concepts. Just like:

varint//定义类型为int的变量v1100   //给v1赋值100

The variable assignment of the Go language is consistent with other programming languages, but the Go language provides multiple assignment functions, such as statements to implement Exchange V1 and V2 variables. The general practice is to need an intermediate variable to complete. Temp=v1,v1=v2,v2=temp. But go can do the following.

package mainimport"fmt"func main() {    varint//定义类型为int的变量v1    v1 = 100    var v2 = 200    fmt.Println("v1:", v1)    fmt.Println("v2:", v2)    fmt.Println("交换v1,v2")    v2, v1 = v1, v2    fmt.Println("v1:", v1)    fmt.Println("v2:", v2)}

Constant

Define, declare

A constant is a value that is known and cannot be changed during compilation. The declaration of a constant is similar to a variable, except that it uses the const keyword.
Constants can be characters, strings, booleans, or numeric values.
Constants cannot be used: = Syntax declaration.

package mainimport"fmt"const Pi = 3.14func main() {    const"世界"    fmt.Println("Hello", World)    fmt.Println("Happy""Day")    consttrue    fmt.Println("Go rules?", Truth)}

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.

package mainimport"fmt"func main() {    const// iota被重设为0        iota// c0 == 0        iota// c1 == 1        iota// c2 == 2    )    fmt.Println("c0", c0)    fmt.Println("c1", c1)    fmt.Println("c2", c2)}


If the expression of the two Const assignment statement is the same, then the latter assignment expression can be omitted. As a result, the first two const statements above can be abbreviated to

const (         // iota被重设为0     iota       // c0 == 0     c1              // c1 == 1     c2              // c2 == 2 )

The result of the above two returns is the same.

Type

I started to touch go first to understand the types of go.
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
    • Strings: String
    • Character Type: Rune

In addition, the go language supports the following composite types:

    • Pointer (pointer)
    • Arrays (Array)
    • Slicing (slice)
    • Dictionary (map)
    • Channel (Chan)
    • struct (struct)
    • Interface (interface)
    • Fault Type: Error

Boolean type

The Boolean type in the Go language is basically the same as other languages, the keyword is bool, the value must be true or false, and automatic or coerced type conversions are not supported.

Integral type

Shaping is basically the most basic type of all programming languages.

It is important to note that, like int and int32 are considered to be two different types in the go language, the compiler does not help you do the type conversion automatically. If you want the conversion to be done manually by yourself, the precision will be lost when casting.
For integral types, there are numerical calculations (+ 、-、 *,/,%), and comparison operations (>, <, = =, >=, <=,! =). This is the same as most other languages and is exactly the same as C, Java, and so on. And the Go integral type also supports bit operations.

Floating point Type

Floating-point types are used to represent data with decimal digits, and the floating-point type in the go language uses the IEEE-754 standard expression. Includes two types of float32 and float64. Where float32 is equivalent to the float type of C, float64 is equivalent to the double type of the C language.

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). For a complex z = complex (x, y), it is possible to get the real part of the complex by using the go language built-in function real (z), which is X, which obtains the imaginary part of the complex by Imag (Z), that is, Y.

String

The

String is a basic type for all programming languages, and go is no exception.

package  Main import   "FMT"  func  Main () {var  str1 string  //definition  str1 = " Hello "  //assignment  char: = Str1[0 ] //gets the first character of the  FMT. Printf ( "string%s length%d\n" , str1, len  (str1)) //gets the first character  FMT. Printf ( "C String%s first character%c\n" , str1, char) str2: =  "world" 
     //initializes the  FMT. Println (str1 + str2) //string connection operation }  

Above the operation of the string is defined, initialized, assigned, calculated length, get the first character, string connection operation. The length of the string is used by a go language built-in function len (). It can also be seen that the go fetch string byte can be the same as the array, directly through the subscript.

Character type

Supports two character types in the go language, one is byte (which is actually an alias of Uint8), represents the value of a single byte of the UTF-8 string, and the other is Rune, which represents a single Unicode character. 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.
In go, the bottom string is stored in a byte array and cannot be changed. If you use string to store Unicode, that is, if you have Chinese, the subscript is inaccessible because you can only get a byte, and the kanji requires 3 bytes.

package mainimport"fmt"func main() {    varstring    "Go语言"    char := str1[2]    fmt.Printf("字符串%s长度%d\n"len(str1))    fmt.Printf("c字符串%s第3个字符%c\n", str1, char)}


The output shows that the "Go language" length is 8, because Chinese characters are stored at 3 bytes. It is not the "language" word that is obtained by subscript.
This is to get the results you want, you need to use Rune. Rune is a byte combination.

package mainimport"fmt"func main() {    varstring    "Go语言"    r := []rune(str1)    fmt.Printf("字符串%s长度%d\n"len([]rune(str1)))    fmt.Printf("c字符串%s第3个字符%c\n", str1, r[2])}


This will take the desired result.

Here first, here are some of the basic types of go support. About compound types See you next time. Through to the current understanding, you can find that go is still a lot of grammatical sugar, many of the writing is different from the language of Java, it seems to draw on a lot of languages like Python, as simple as possible. Have time to get to know the philosophy of the Go language design.

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.