Go a little everyday language - variables, constants, operators resolve

Go a little everyday language - variables, constants, operators resolve

Foreword

Simple mentioned earlier about the basic syntax and data types in Go, Go language generally understand the composition of the program, and this article will describe the variables involved in almost all programming languages, constants, and operators related content.

A variable

What is variable?

The Professional Glossary: ​​computer languages ​​can store the results or values ​​can be represented abstract concepts. Variables can be accessed via the variable name. Go language variables consist of letters, numbers, underscores, the first letter can not be a number. Familiar with the Ha ~

I understand: When I was writing a program requires the use of a value, and I always wanted to be reused, and sometimes this value will change and so on, so I need to declare a variable is assigned the value.

How to declare variables?

The general format of variable declaration:

var 变量名 变量类型

var: variable declaration keyword, declare a variable representation

Followed by the variable name, and finally the type of the variable (such as int)

Of course, there are other changes in format, we look at the direct instance:

Examples of variable format written 1.1 - 1

package main
var a1 int = 10
var a2 = "hello world"
var b1 = 11
var b2 string = "你好,世界"
//c1 := 12 //这种不带声明格式的只能在函数体中出现,否则会报错:non-declaration statement outside function body
var c2 bool

func main(){
        println(a1,a2,b1,b2,c2)
        c1 := 12 //这种变量声明要注意:c1变量没有被提前声明过才可以这样赋值
        println(c1)
}

operation result:

10 hello world 11 Hello, world false
12

Of course, you can also declare variables together, will automatically infer the type of a variable during program execution (similar to Python)

Variable format written line 1.2 Example 2

package main
//写法一:
var v1, v2, v3 int
//写法二:
var v11, v22, v33 = 4, 5, "hello"
//写法三:(需写在全局变量中,不可以写在函数体内部)
var (
        vv1 int 
        vv2 bool = true
)
func main(){
        v1, v2, v3 = 1, 2, 3
        println(v1,v2,v3)
        println(v11,v22,v33)
        println(vv1,vv2)
}

operation result:

1 2 3
4 5 hello
0 true

Additional information:

Omitting the variable type is automatically inferred by the system initialization variable declaration statement written on the var keyword is actually a bit redundant, so we they can be abbreviated as a: = 50 or b: = false. The compiler will automatically infer this type int a, b type bool.

This short form of variable declarations need to note the following:

  • Can only be used inside the body of the function;
  • Same block of code, not repeat variable declaration;

In addition, variables need to be declared after use (all methods are the same); When declaring a local variable (inside the function body), without use, will compile error; but global variables can not be used.

Value types and reference types

Value Type

int, float, bool, string belong to these basic types of value type. A typical characteristic value type is: we are assigned and stored in a computer, such a procedure is used (understood to do first):

Definition of variables in memory, the value of the type of variables are stored in the stack, assignment, is a relationship between the value of the value of a copy of a copy of this content then given to the variable, the variable (type value) of copied: the value of variables in memory that point directly.

Can be obtained through the memory address of the variable & variable name, the address of each acquisition may not be the same.

Examples of value type variable memory address 1.3--

package main

var a int = 10

func main(){
    println(a)
    println(&a)
}

operation result:

10
0x4a4018

Reference type (as first understand)

Go language reference types are: mapping (map), an array slice (slice), the channel (channel), methods and functions.

Go language exists garbage collector, so when a local variable is no longer used will be recycled out, this time the life cycle of local variables determined by their scope. For managing the life cycle of local variables, we need to use the pointer, you can make use of the pointer variable corresponding to the life cycle of the independence and scope.

Pointer variable to control the life cycle, not affected by the scope of the other variables in the process, to minimize the cost of transmission, and may modify the contents of a variable, rather than the value of the copy operation. Of course, a pointer is a variable representing the stored (saved) in the memory address of another variable, and any variable are stored pointer memory address can be modified by the content of the pointer.

& * And understand:
  • Operator &: as when binary operator, a bitwise AND operation; when used as a unary operator, is returned to the variable address memory
  • * Operator: When used as a binary operator is multiplication operation; as when unary operators (dereference operator), the return value of the pointer variable, in fact, the pointer reference variable release, return the value of this variable.

Examples of the creation and use of pointer 1.4 -

package main
import "fmt"

func main(){
    a := 3
    p := &a //获取变量a的内存地址,并且将其赋值给p
    fmt.Printf("a的值为: %v,a的指针为: %v,p指向的变量的值为: %v\n",a,p,*p)
}

operation result:

~~~ a value: 3, a pointer is: 0xc4200160d8, the value of variable p to point: 3


​   也就是说*p和a的值是相等的,可以交换使用。两者都与同一块内存地址相关联,任意一个变量进行修改操作都会影响到另一个变量的值,但是若变量p被赋值其他变量的指针就不行了

### 空指针

​   当一个指针被定义后没有分配到任何变量,值就为nil,叫做空指针。nil在概念上和其它语言的null、None、nil、NULL一样,都指代零值或空值。

#### 实例1.5——空指针

~~~go
package main

import "fmt"
func main() {
   var  ptr *int
   fmt.Printf("ptr 的值为 : %x\n", ptr  )
}

~~~ Run Results: PTR value: 0


# 二、常量

​   Go语言常量就是值的标识符,程序运行时,不会被修改。常量中的数据类型只可以是bool型、数字型和字符串型。

常量定义格式:

~~~go
const identifier [type] = value

Explained: const - keyword indicates that the variable is defined as constants can not be changed

Examples of constant defines the use of 2.1 -

package main

import "fmt"
const m string = "hello" //显式类型定义
const n = "world" //隐式类型定义

func main() {
    const LENGTH int = 10
    const WIDTH int = 5
    var area int
    const a, b, c = 1, false, "str" //多重赋值

    area = LENGTH * WIDTH
    fmt.Printf("面积为 : %d\n", area)
    println(m, n)
    println(a, b, c)
    //m = "wrong" //错误示范
    //println(m) //编译报错:cannot assign to m,说明const变量不可以更改
}

operation result:

面积为 : 50
hello world
1 false str

Of course, also be used as enumeration constants

const (
    Yes = 0
    No = 1
    Notsure = 2

iota

iota, a special constant, can be considered to be a modified compiler constants

Examples 2.2 - iota

package main

import "fmt"

func main() {
    const (
            a = iota   //0
            b          //1
            c          //2
            d = "ha"   //独立值,iota += 1
            e          //"ha"   iota += 1
            f = 100    //iota +=1
            g          //100  iota +=1
            h = iota   //7,恢复计数
            i          //8
    )
    fmt.Println(a,b,c,d,e,f,g,h,i)
}

operation result

~~~ 0 1 2 100 100 has been August 7


从给出结果的现象可以知道:

1、在go语言编程中,iota是一个会在程序运行过程中自动变换的常量;

2、在给const修饰的变量赋值时,每次会隐藏性自增1,无论是不是在赋予给定的值;

3、当赋予给定的值给变量后,该变量之后的变量又未赋予其他的给定的值时,其后面的变量的值和该变量相等;就如上面的d和e,f和g ;但是有例外(看下面的例子)

4、而当变量回归赋值iota时,将按照自增的结果赋值给变量。

如下面的例子:

#### 实例2.3——有趣的iota

~~~go
package main

import "fmt"
const (
    i=1<<iota   //"<<"——此符号表示的位运算符,左移;此时对应关系为i——>1<<iota:1左移0位;则i的值为1  
    j=3<<iota   //此时对应关系为:j——>3<<iota为3,iota的值为1,则左移1位,即0011——>0110=6  
    k           //但是此时关系为k——>3<<iota,而不是6<<2,iota为2,k的值为12
    l 
    m=iota
)  
func main() {    
    fmt.Println("i=",i)   
    fmt.Println("j=",j)   
    fmt.Println("k=",k)
    fmt.Println("l=",l)
    fmt.Println("m=",m)
} 

operation result:

i= 1
j= 6
k= 12
l= 24
m= 4

Third, the operator

Programming language has nearly all operators, operator action is nothing less than two: mathematical and logical operations

Go language has built-in operators: arithmetic operators, relational operators, logical operators, bit operators, assignment operators, other operators

1, arithmetic operators

Comprising: a +, -, *, /,%, +, - represents the modulo three, increment, decrement

Example 3.1 - arithmetic operators Demo

package main

import "fmt"

func main() {

   var a int = 21
   var b int = 10
   var c int

   c = a + b
   fmt.Printf("加法:  c 的值为 %d\n", c )
   c = a - b
   fmt.Printf("减法:  c 的值为 %d\n", c )
   c = a * b
   fmt.Printf("乘法:  c 的值为 %d\n", c )
   c = a / b
   fmt.Printf("除法:  c 的值为 %d\n", c )
   c = a % b
   fmt.Printf("取余:  c 的值为 %d\n", c )
   a++
   fmt.Printf("a自增:   值为 %d\n", a )
   a--
   fmt.Printf("a自减:   值为 %d\n", a )
}

operation result:

加法:  c 的值为 31
减法:  c 的值为 11
乘法:  c 的值为 210
除法:  c 的值为 2
取余:  c 的值为 1
a自增:   值为 22
a自减:   值为 21

2, relational operators

包括 == 、!=、>、<、 >=、 <= 分别对应:判断是否等于,是否不等于,大于,小于,大于等于,小于等于

This article, which is not code demonstrates, because it involves a controlled flow statement speaks

3, logical operators

The chart lists all logical operators in Go. Assuming that A is True, B is False.

Go a little everyday language - variables, constants, operators resolve

4, bitwise operator

Operator site of action is an integer bits in the memory operation.

The following table lists the bit operators &, |, and ^ is calculated: shows the relation "and or" in logical

Go a little everyday language - variables, constants, operators resolve

to sum up:

&: It is true is true on both sides

|: It is false is false on both sides

^: Different sides to be true

Of course, the above-described left, right calculated. for example:

60 & 13 The results are: 12, 60 and 13 is calculated into a binary do bitwise AND, i.e.: 00111100 & 00001101 = 00001100

60 | 13 results as follows: 61, 60 and 13 is calculated into a binary bitwise OR do, namely: 0011 1100 | 0000 1101 = 0011 1101

5, the assignment operator

Assignment operator as follows:

Go a little everyday language - variables, constants, operators resolve

6, other operators

Mainly & mentioned above and *, respectively for the return and variable storage address pointer variables

Operator Precedence

Some operators have the higher priority, binary operators are operational direction from left to right. The following table lists all the operators and their priority, from highest to lowest priority from top to bottom on behalf :( recommend the use of parentheses when programming to enhance the priority, but also to enhance the readability of code)

Go a little everyday language - variables, constants, operators resolve

IV Summary

This article describes the language go on variables, constants, content operators. Note that variables defined in the variable format and location, especially in a concise format, followed by a constant need to pay attention to a special constant iota. Finally, there is operator, need to understand sentiment in case of actual programming.

Guess you like

Origin blog.51cto.com/14557673/2484879