Go基础语法

Go基础语法

文中大部分示例代码来自Go by Example

Hello World

package main

import "fmt"

func main() {
	fmt.Println("hello world")
}

Values

package main

import "fmt"

func main() {
	fmt.Println("go" + " lang")
	fmt.Println("1 + 1 = ", 1 + 1)
	fmt.Println("7.0 / 3.0 = ", 7.0 / 3.0)
	fmt.Println(true && false)
	fmt.Println(true || false)
	fmt.Println(!true)
}

Variables

package main

import "fmt"

func main() {
	var a ="initial"
	fmt.Println(a)
	
	// 一次声明多个变量
	var b, c int = 1, 2
	fmt.Println(b, c)
	
	// 类型推断
	var d = true
	fmt.Println(d)
	
	// zero-valued
	var e int
	fmt.Println(e)
	
	// var f string  = "apple"
	// := 这种比较常用
	f := "apple"
	fmt.Println(f)
	
}

Constants

package main

import (
	"fmt"
	"math"
)

const s string = "constant"

func main() {
	
	fmt.Println(s)
	
	const n = 500000000
	fmt.Println(math.Sin(n))

	const d = 3e20 / n
	fmt.Println(d)
	
	fmt.Println(int64(d))
}

For

package main

import (
	"fmt"
)

func main() {
	
	i := 1
	
	for i <= 3 {
		fmt.Println(i)
		i = i + 1
	}
	
	for j := 7; j < 9; j++ {
		fmt.Println(j)
	}
	
	for {
		fmt.Println("loop")
		break
	}
	
	for n := 0; n <= 10; n++ {
		if n % 2 == 0 {
			continue
		}
		fmt.Println(n)
	}
}

If/Else

package main

import (
	"fmt"
)

func main() {
	
	if 7 % 2 == 0 {
		fmt.Println("7是偶数")
	} else {
		fmt.Println("7是奇数")
	}
	
	if 8 % 4 == 0 {
		fmt.Println("8能被4整除")
	}
	
	if num := 9; num < 0 {
		fmt.Println(num, "is negative")
	} else if num < 10 {
		fmt.Println(num, "has 1 digit")
	} else {
		fmt.Println(num, "has multiple digits")
	}
	
	// 上面if中声明的变量不能在其他地方使用
	// fmt.Println(num)
	
	// go 中没有三目运算符 ? :
	
}

Switch

package main

import (
	"fmt"
	"time"
)

func main() {
	
	i := 2
	fmt.Println("Write ", i, " as ")
	switch i {
		case 1:
			fmt.Println("one")
		case 2:
			fmt.Println("two")
		case 3:
			fmt.Println("three")
	}
	
	switch time.Now().Weekday() {
		case time.Saturday, time.Sunday: {
			fmt.Println("It's the weekend")
		}
		default:
			fmt.Println("It's a weekday")
	}
	
	t := time.Now()
	fmt.Println(t.Hour())
	switch {
		case t.Hour() < 12: {
			fmt.Println("It's before noon")
		}
		default: 
			fmt.Println("It's after noon")
	}
	
	whatAmI := func(i interface{}) {
		switch t := i.(type) {
			case bool:
				fmt.Println("I'm a bool")
			case int:
				fmt.Println("I'm an int")
			default:
				fmt.Printf("Don't know type %T\n", t)
		}
	}
	
	whatAmI(true)
	whatAmI(1)
	whatAmI("hi")
	
}

Arrays

package main

import (
	"fmt"
)

func main() {
	var a [5]int
	fmt.Println("emp:", a)
	
	a[4] = 100
	fmt.Println("set:", a)
	fmt.Println("get:", a[4])
	
	b := [5]int{1, 2, 3, 4, 5}
	fmt.Println("dcl:", b)
	
	var twoD [2][3]int
	for i := 0; i < 2; i++ {
		for j := 0; j <3; j++ {
			twoD[i][j] = i + j
		}
	}
	fmt.Println("2d:", twoD)
	
}

Slices

package main

/*
https://gobyexample.com/slices
slice内部实现 https://go.dev/blog/slices-intro

切片 value := []类型 {}
数组 value := [数组长度]类型 {}
数组与切片的区别:
1、声明数组需要指定数组长度,切片则不需要;
2、作为函数参数时,数组传递的是数组的副本,切片传递的是指针。
*/
import (
	"fmt"
)

func main() {
	
	s := make([]string, 3)
	fmt.Println("emp:", s)
	
	s[0] = "a"
	s[1] = "b"
	s[2] = "c"
	fmt.Println("set:", s)
	fmt.Println("get:", s)
	
	fmt.Println("len:", len(s))
	
	// append
	s = append(s, "d")
	s = append(s, "e", "f")
	fmt.Println("apd:", s) // [a b c d e f]
	
	// copy
	c := make([]string, len(s))
	copy(c, s)
	fmt.Println("cpy:", c)
	
	// slice[low:high] 包括low,不包括high
	l := c[2:4]
	fmt.Println("sl1:", l)
	
	l = c[2:]
	fmt.Println("sl2:", l)
	
	l = c[:4]
	fmt.Println("sl3:", l)
	
	t := []string{"g", "h", "i"}
	fmt.Println("dcl:", t)
}

Maps

package main

import (
	"fmt"
)

func main() {

	// make(map[key-type]val-type)
	m := make(map[string]int)
	
	// name[key] = val
	m["k1"] = 7
	m["k2"] = 13
	fmt.Println("map:", m)

	v1 := m["k1"]
	fmt.Println("v1:", v1)
	
	fmt.Println("len:", len(m))
	
	//delete(m, "k2")
	//fmt.Println("map:", m)
	
	/* 
	判断key是否存在
	第一个返回值是key对应的value,使用下划线_表示忽略返回值
	第二个返回值表示key是否存在
	*/
	_, prs := m["k2"]
	fmt.Println("prs:", prs)
	
	// 声明并初始化map
	n := map[string]int{"foo": 1, "bar": 2}
	fmt.Println("map:", n)
}

Range

package main

import (
	"fmt"
)

func main() {
	nums := []int{1, 2, 3, 4}
	sum := 0
	// range 返回两个值,第一个值表示slice下标,第二个表示slice下标对应的值
	for _, num := range nums {
		sum += num
	}
	fmt.Println("sum:", sum)
	
	for i, num := range nums {
		if num == 3 {
			fmt.Println("index:", i)
		}
	}
	
	kvs := map[string]string{"a": "apple", "b": "banana"}
	for k, v := range kvs {
		fmt.Printf("%s -> %s\n", k, v)
	}
	
	for k := range kvs {
		fmt.Println("key:", k)
	}
	
	for i, c := range "go" {
		fmt.Println(i, c)
	}

}

Functions

package main

import (
	"fmt"
)

func plus(a int, b int) int {
	return a + b
}

func plusPlus(a, b, c int) int {
	return a + b + c
}

func main() {

	res := plus(1, 2)
	fmt.Println("1 + 2 =", res)

	res = plusPlus(1, 2, 3)
	fmt.Println("1 + 2 + 3 =", res)
	
}

Multiple Return Values

package main

import (
	"fmt"
)

// 多个返回值
func vals() (int, int) {
	return 3, 7
}

func main() {
	
	a, b := vals()
	fmt.Println(a, b)
	
	_, c := vals()
	fmt.Println(c)	
}

Variadic Functions

package main

import (
	"fmt"
)

// 可变参数
func sum(nums ...int) {
	fmt.Print(nums, " ")
	
	total := 0
	for _, num := range nums {
		total += num
	}
	fmt.Println(total)
}


func main() {
	
	sum(1, 2, 3)
	
	// slice
	nums := []int{1, 2, 3, 4}
	sum(nums...)
	
}

Closures

package main

import (
	"fmt"
)

// 闭包(匿名函数)
func intSeq() func() int {
	i := 0
	// 返回一个函数
	return func() int {
		i++
		return i;
	}
}

func main() {
	nextInt := intSeq()
	fmt.Println(nextInt())
	
	fmt.Println(nextInt())
	fmt.Println(nextInt())
	fmt.Println(nextInt())

	nextInts := intSeq()
	fmt.Println(nextInts())
}

Recursion

package main

import (
	"fmt"
)

// 递归
func fact(n int) int {
	if n == 0 {
		return 1
	}
	return n * fact(n-1)
}

func main() {

	res := fact(4)
	fmt.Println(res)
	
	// 闭包,先声明再定义
	var fib func(n int) int
	
	fib = func(n int) int {
		if n < 2 {
			return n
		}
		return fib(n-1) + fib(n-2)
	}
	
	fmt.Println(fib(7))

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值