Go基础及语法(二)

运算符

算术运算符

package main

import "fmt"

func main() {
	a := 6
	b := 2
	c := a + b //加
	d := a - b //减
	e := a * b //乘
	f := a / b //除
	fmt.Println(c, d, e, f) //8 4 12 3
}

逻辑运算符

package main

import "fmt"

func main() {
	a := true 
	b := false
	c := a && b          //与
	d := a || b          //或
	e := !a              //非
	fmt.Println(c, d, e) //false true false
}

位运算符

package main

import "fmt"

func main() {
	a := 0b0101
	b := 0b0110
	c := a & b //与
	d := a | b //或
	e := a ^ b //异或
	f := b >> 1 //右移
	g := b << 1 //左移
	fmt.Println(c, d, e, f, g) //4 7 3 3 12
}

赋值运算符

package main

import "fmt"

func main() {
	a := 6
	b := 2
	a += b         //加等于:a = 6 + 2 = 8
	a -= b         //减等于:a = 8 - 2 = 6
	a *= b         //乘等于:a = 6 * 2 = 12
	a /= b         //除等于:a = 12 / 2 = 6
	a++            //a=6+1=7
	a--            //a=7-1=6
	fmt.Println(a) //6
}

比较运算符

package main

import "fmt"

func main() {
	a := 6
	b := 2
	c := a < b //小于
	d := a <= b //小于等于
	e := a > b //大于
	f := a >= b //大于等于
	g := a == b //等于
	h := a != b //不等于
	fmt.Println(c, d, e, f, g, h) //false false true true false true
}


数组(Array)

package main

import "fmt"

func main() {
	a := []int{1, 2, 3} //中括号里可填数,代表数组预留大小,可不填,为自适应
	b := [][]int{[]int{1, 2}, []int{3, 4}}
	c := make([]int, 3, 4) //make开辟一个内存空间
	fmt.Println(a, b, c)   //[1 2 3] [[1 2] [3 4]] [0 0 0]
	a = append(a, 4)       //在数组a后插入元素4
	fmt.Println(a)         //[1 2 3 4]
	var d = make([]int, 5)
	copy(d, a)     //拷贝
	fmt.Println(d) //[1 2 3 4 0]
	//遍历方法一
	for k, v := range d {
		fmt.Printf("[%d %d],", k, v) //[0 1],[1 2],[2 3],[3 4],[4 0],
	}
	//遍历方法二
	for i := 0; i < len(d); i++ {
		fmt.Printf("%d,", d[i]) //1,2,3,4,0,
	}
}

指针

package main

import "fmt"

func main() {
	a := "a"
	b := &a //&指向内存地址,*指向内存地址上的内容
	fmt.Print(a, *b, b) //a a 0xc...
}


map

map存储的是键值对的数据
map遍历与数组类似

package main

import "fmt"

func main() {
	a := make(map[string]string) //初始化map
	a["key1"] = "value1"         //增/改键值对
	a["key2"] = "value2"
	fmt.Println(a)                               //map[key1:value1 key2:value2]
	fmt.Println(a["key2"])                       //value2
	fmt.Printf("%s, %T\n", a["key3"], a["key3"]) //, string(没有对应的key也不会报错)
	k1, v1 := a["key2"]
	fmt.Println(k1, v1) //value2 true
	delete(a, "key2")   //删除键值对
	k2, v2 := a["key2"]
	fmt.Println(k2, v2) // false
}

posted @ 2021-01-18 15:04  _Biko  阅读(85)  评论(0编辑  收藏  举报