Go语言快速上手-基础语法(一) | 青训营笔记

140 阅读1分钟

这是我参与「第三届青训营 -后端场」笔记创作活动的的第1篇笔记。

1、配置开发环境

(1)安装Golang

通过国内的镜像下载:studygolang.com/dl

(2)配置Golang的IDE

我使用的是GoLand,直接在官网下载即可,但还需安装Go插件:访问 marketplace.visualstudio.com/items?itemN… 安装后即可。

2、Go的基础语法

让我们从Hello World开始吧!

package main

import (
	"fmt"
)

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

编译运行:

直接运行:go run example/01-hello/main.go
编译成二进制文件:go build example/01-hello/main.go
./main

if-else

package main

import "fmt"

func main() {

	if 7%2 == 0 {
		fmt.Println("7 is even")
	} else {
		fmt.Println("7 is odd")
	}

	if 8%4 == 0 {
		fmt.Println("8 is divisible by 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")
	}
}

switch分支

package main

import (
	"fmt"
	"time"
)

func main() {

	a := 2
	switch a {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("two")
	case 3:
		fmt.Println("three")
	case 4, 5:
		fmt.Println("four or five")
	default:
		fmt.Println("other")
	}

	t := time.Now()
	switch {
	case t.Hour() < 12:
		fmt.Println("It's before noon")
	default:
		fmt.Println("It's after noon")
	}
}

for

package main

import "fmt"

func main() {

	i := 1
	for {
		fmt.Println("loop")
		break
	}
	for j := 7; j < 9; j++ {
		fmt.Println(j)
	}

	for n := 0; n < 5; n++ {
		if n%2 == 0 {
			continue
		}
		fmt.Println(n)
	}
	for i <= 3 {
		fmt.Println(i)
		i = i + 1
	}
}