[GO Language Fundamentals] Basic skills of GO basic operators, variables and constants (3)

Operator

Operators are used to perform mathematical or logical operations while the program is running.

The built-in operators of the Go language are: arithmetic operators , assignment operators , logical operators , relational operators , bitwise operators, and other operators

Go language does not support ternary operators.

Arithmetic Operator

Arithmetic operators perform operations on numeric variables, such as addition, subtraction, multiplication, and division, which are used a lot in Go programs.

The following table lists all the arithmetic operators in Go language. Suppose the value of A is 10 and the value of B is 3.

Operator description Example (A = 7 B = 2)
+ Positive sign + B = 2
- negative - B = -2
+ Add up A + B = 9
- Subtract A - B = 5
* Multiply A * B = 14
/ Divide A / B = 3
% Surplus A % B = 1
++ Self-increasing A++ = 8
Decrement A-- = 6
+ String splicing “Hell” + “lo” = “hello”

For the division sign "/", there is a difference between integer division and decimal division: when dividing integers, only the integer part is kept and the decimal part is discarded (rather than rounding). For example: 10/3 = 3; 10.0 / 3 = 3.333; 18/5 = 3

    var res int = 10 / 3 //正确
    var res int = 10.0 / 3 //错误,右边计算的结果是float类型,而左边的变量是int类型,不可以赋值

When taking the modulus of a number (for example: A% B), it can be equivalent to A% B = A-A / B * B, so that we can see an essential operation of modulus. -10% 3 and 10% -3 results are different

    -10 % 3 = -10 - ( -10 / 3) * 3

            = -10 - (-3 * 3)

            = -10+9

        = -1

    10 % -3 = 10 - (10 / -3) * -3
        = 10 - (-3) * -3
        = 10 - 9
        = 1

Golang's increment and decrement can only be used as an independent statement, it cannot appear on the right side of the assignment statement (for example: var res int = n++), nor can it be used like if i++> 0 {}

Golang's ++ and-can only be written after the variable, not before the variable, that is: only a++, not ++a

The designer of Golang removed the confusing writing method of self-increment and self-decrement in C/Java, making Golang more concise and unified. (compulsory)

Relational operator

The results of relational operators are all bool types, either true or false; relational expressions are often used in the condition of if structure or the condition of loop structure

The following table lists all the relational operators of the Go language. Suppose the value of A is 10 and the value of B is 20.

Operator description Instance
== Check whether the two values ​​are equal, and return true if they are equal, otherwise return false. (A == B) is false
!= Check whether the two values ​​are not equal, and return true if they are not equal, otherwise return false. (A != B) is true
> Check whether the value on the left is greater than the value on the right, and return true if it is, otherwise return false. (A> B) is false
< Check whether the value on the left is less than the value on the right, and return true if it is, otherwise return false. (A < B) 为 true
>= Check whether the value on the left is greater than or equal to the value on the right, if it is true, otherwise it returns false. (A >= B) is false
<= Check whether the left value is less than or equal to the right value, if it is true, otherwise it returns false. (A <= B) 为 true

Logical Operators

Used to connect multiple conditions (in general, relational expressions), the final result is also a bool value.

The following table lists all logical operators in Go language. Assume that the value of A is True and the value of B is False.

Operator description Instance
&& Logical AND operator. If both operands are True, the condition is True, otherwise it is False. (A && B) 为 False
|| Logical OR operator. If the operands on both sides have a True, the condition is True, otherwise it is False. (A || B) is True
! Logical NOT operator. If the condition is True, the logical NOT condition is False, otherwise it is True. !(A && B) 为 True
  • Short circuit and short circuit or

&& is also called short-circuit and: if the first condition is false, the second condition will not be judged, and the final result is false
|| also called short-circuit or: if the first condition is true, the second condition will not be judged , The final result is true

Assignment operator

Assignment operator is to assign the value after a certain operation to the specified variable.

Operator description Instance
= Simple assignment operator, assigns the value of an expression to an lvalue C = A + B assigns the result of the A + B expression to C
+= Assign after adding C += A is equivalent to C = C + A
-= Assign after subtraction C -= A is equal to C = C-A
*= Assign after multiplying C = A is equal to C = CA
/= Assign after dividing C /= A is equal to C = C / A
%= Assign after the remainder C %= A is equivalent to C = C% A
<<= Assign after shift left C <<= 2 等于 C = C << 2
>>= Assign after right shift C >>= 2 is equivalent to C = C >> 2
&= Bitwise and post assignment C &= 2 is equal to C = C & 2
^= Assignment after bitwise XOR C ^= 2 is equal to C = C ^ 2
|= Bitwise or post-assignment C |= 2 is equivalent to C = C | 2

Bitwise operator

Bit operators operate on the binary bits of integers in memory. (If you don't understand here, you can first see 008. Computer base introduction)

The following table lists the calculations of the bitwise operators &, |, and ^:

p q p & q n | m p q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assuming that A = 60; B = 13; its binary numbers (to find their complement, in fact, to perform operations on the complement) is converted to:

    A   = 0011 1100

    B   = 0000 1101

    -----------------

    A&B = 0000 1100

    A|B = 0011 1101

    A^B = 0011 0001

The computer uses one's complement for calculation

        A+B
        A的原码为: 0011 1100   
        A的反码为: 0011 1100
        A的补码为: 0011 1100
        B的原码为: 0000 1101  
        B的反码为: 0000 1101
        B的补码为: 0000 1101
        A + B
            0011 1100
            0000 1101
        --------------
            0100 1001
            
        0100 1001转换为10进制整数就是73
            
        A-B = A + (-B)
        A的原码为: 0011 1100   
        A的反码为: 0011 1100
        A的补码为: 0011 1100
        -B的原码为: 1000 1101  
        -B的反码为: 1111 0010
        -B的补码为: 1111 0011
        A - B = 
            0011 1100
            1111 0011
        --------------
            0010 1111

        0010 1111转换为10进制整数就是47

        需要注意的是如果得到的结果是正数,则补码就是原码,但是如果得到的结果是负数,则需要将补码-1取反变成原码后再转换成整数
        B - A    
        -A的原码为: 1011 1100
        -A的反码为: 1100 0011
        -A的补码为: 1100 0100
        B的原码为: 0000 1101  
        B的反码为: 0000 1101
        B的补码为: 0000 1101
        B - A =     
            1100 0100
            0000 1101
        --------------
            1101 0001
        根据补码符号位可以看出结果为负数,所以需要先-1转换为反码1101 0000,然后符号位不变,取反为原码为1010 1111即为-47   

Other operators

Operator description Instance
& Return variable storage address &a; will give the actual address of the variable.
* Pointer variable. *a; is a pointer variable

Operator precedence

Operators have different priorities. The so-called priority is the order of operations in expression operations. As shown in the table below, the precedence of operators on the previous line is always better than that of the next line.

classification description Relevance
suffix () [] -> . ++ – Left to right
Monocular + - ! ~ (type) * & sizeof Right to left
Multiply and divide * / % 左到右
加减 + - 左到右
移位 << >> 左到右
关系 < <= > >= 左到右
相等 == != 左到右
按位AND & 左到右
按位XOR ^ 左到右
按位OR | 左到右
逻辑AND && 左到右
逻辑OR || 左到右
赋值运算符 = += -= *= /= %= >>= <<= &= ^= |= 右到左
逗号 , 左到右

基本顺序为:括号 > 单目运算 > 算术运算符 > 移位运算符 > 关系运算符 > 位运算符 > 逻辑运算符 > 赋值运算符 > 逗号

  • 只有单目运算符、赋值运算符是从右向左运算的。

变量与常量

变量(Variable)

变量表示内存中的一个存储区域,该区域有自己的名称(变量名)和类型(数据类型)。

方法 1
    var a int       //声明          声明后若不赋值,使用默认值
    a = 10          //赋值
    fmt.Println(a)  //使用

方法 2
    var a = 10      //声明并赋值    根据值自行判定数据类型(类型推导)
    fmt.Println(a)  //使用  

方法 3
    a := 10         //声明并赋值    “:=” 方式赋值时,必须是一个没有声明过的变量,否则会导致编译错误 no new variables on left side of :=
    fmt.Println(a)  //使用

golang 提供多变量声明与赋值

//一次性声明多个全局变量[在go中函数外部定义变量就是全局变量]
方式一:
    var a = 1
    var b = 2
    fmt.Println(a, b) 
 
方式二:
    var (
        a    = 1
        b    = 2
    )
    fmt.Println(a, b) 

方式三:
    var a, b = 1, 2
	fmt.Println(a, b)

方法四:
    a, b := 1, 2
	fmt.Println(a, b)

匿名变量(anonymous variable)

在使用多重赋值时,如果不需要在左值中接收变量,可以使用匿名变量
匿名变量的表现是一个下画线_,使用匿名变量时,只需要在变量声明的地方使用下画线替换即可。
匿名变量不占用命名空间,不会分配内存。匿名变量与匿名变量之间也不会因为多次声明而无法使用。

提示:在 Lua 等编程语言里,匿名变量也被叫做哑元变量。

    func GetData() (int, int) {
        return 100, 200
    }
    a, _ := GetData()
    _, b := GetData()
    fmt.Println(a, b)

常量(constant)

golang中,常量是指编译期间运算得出且不可改变的值。
golang常量定义的关键字为const。
常量中的数据类型只能是布尔型、数字型(整数型、浮点型和复数)和字符串型。

    // 定义单个常量
    const Pi float64 = 3.14159265358979323846

    // 定义多个常量
    const (
        Size int64 = 1024
        Eof  int64 = -1
    )

golang常量定义可以限定常量类型,也可以不限定。如果常量定义时没有限定类型,那么它与字面常量一样,是一个无类型常量。

    // 定义单个常量
    const Pi = 3.14159265358979323846 // 无类型浮点常量

    // 定义多个常量
    const (
        Size = 1024 // 无类型整型常量
        Eof  = -1   // 无类型整型常量
    )

无论是变量还是常量,不同类型的都不能显式的声明在一行:

    var a int, b float32 = 1, 2.4   //编译器不通过
    const c int, d float32 = 3, 4.4 //编译器不通过
    const c, d float32 = 3, 4 //编译通过(此时c和d都是float32类型)
    const c, d = 3, 4.4  //编译通过(此时c是int类型,d是float64类型)

当我们定义常量时,如果多个常量的值相同,后面的常量可以直接不赋值,默认等同于上面已赋值的常量的值

package main

import "fmt"
const (
    a = "itbsl"
    c
    d
)
func main() {
    fmt.Println(a, c, d)
}

结果

itbsl itbsl itbsl

我们可以通过reflect.Typeof(变量名)打印变量或常量的类型

常量可以用len()、cap()、unsafe.Sizeof()常量计算表达式的值。常量表达式中,函数必须是内置函数,否则编译不通过,因为在编译期间自定义函数均属于未知,因此无法用于常量的赋值

golang常量定义的右值可以是一个在编译期运算的常量表达式,这与c语言中宏的性质是一样的。

    const Mask = 1 << 3            // correct
    const Path = os.Getenv("PATH") // incorrect : const initializer os.Getenv("PATH") is not a constant

字面常量(literal)

字面常量(literal),是指程序中硬编码的常量。
golang中字面常量是无类型的,只要该字面常量在相应类型的值域范围内,就可作为该类型的常量。

预定义常量

golang预定义了这些常量:true、false和iota

  • true和false

预定义常量true和false所属的基础类型为bool

  • iota
    预定义常量iota所属的基础类型为int
    iota可认为是一个可被编译器修改的常量:在每一个const关键字出现时值重置为0,然后在下一个const出现之前,每出现一次iota,其所代表的数字会自动增1
    如果两个const赋值语句的表达式一样,那么可以省略后一个赋值表达式

枚举

golang并不支持众多其他语言中支持的enum关键字。
在golang中定义枚举值的方式:在const后跟一对圆括号的方式定义一组常量。

Guess you like

Origin blog.csdn.net/weixin_54707168/article/details/113933990