Go语言基础 | 青训营笔记

59 阅读4分钟

这是我参与「第五届青训营 」笔记创作活动的第1天

概述

本篇简记Go语言相关基础语法, 并以三个简单项目实例展示Go语言的实际应用, 因本人接触较多的方向为Java语言, 所以为便于理解, 笔记会以接近Java的形式去记录.

Go语言简介

Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run-time reflection. It's a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language.

Go 语言被设计成一门应用于搭载 Web 服务器, 存储集群或类似用途的巨型中央服务器的系统编程语言. 对于高性能分布式系统领域而言,Go 语言无疑比大多数其它语言有着更高的开发效率, 因此许多公司开始尝试将业务使用Go语言进行开发, 在国内例如字节跳动, 哔哩哔哩.

开发环境

环境部署

Golang的环境部署相对来说比较简单, 这面我使用Windows平台来学习, 就以Windows平台部署环境为例:

首先访问Go语言官网寻找适合自己平台的安装包, 这边我选择Windows平台

屏幕截图 2022-12-15 171841.png

其他平台可以参考官方文档

下载之后默认安装即可, 可以通过在cmd中输入"go version"验证是否安装成功

部分安装教程会提示设置GOPATH环境变量, 作用是修改之后的Go语言项目的依赖安装位置, 即"go get""go install"命令获取的文件的存储位置

配置IDE

IDE可以选择VSCode或者Goland, 我申请过JetBrains的学生认证, 所以这面使用Goland, Goland安装无需特殊配置, 这边不过多介绍

Goland官网

基本语法

Hello World

新建main.go文件, 输入以下代码

package main

import (
   "fmt"
)

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

这将是你的第一个Go语言程序, 你可以在终端中输入"go run .\main.go"运行程序

image.png

或者通过"go build .\main.go"命令将程序构建为可执行文件

第一行的package main代表这个文件是main包的一部分, 而在Go语言中main包是程序的入口

第三行导入了程序的运行所需要的fmt包, fmt包主要用来完成输入输出, 格式化字符串

Package fmt implements formatted I/O with functions analogous to C's printf and scanf.

再下面的main函数通过调用fmt.Println向终端输出"Hello world"

变量

Go是强类型语言, 每个变量都有它的变量类型

对于未明确表明类型的变量, Go语言支持自动推断其类型

可以通过 := 符号声明一个变量

可以使用 const 关键字创建一个常量

var a int = 1
var d = true
var e float64
f := 114.514
const h string = "constant"

流程控制

Go语言的流程控制支持if for switch

值得一提的是这里的switch相对于C来说更为强大, 可以使用任意变量类型, 可以在switch后面不加变量而通过case写条件分支, 你也不用在每个case后面添加break

数据存储

Go语言支持数组, 切片(类似集合), map

//数组
var a [5]int
a[4] = 100
fmt.Println("get:", a[2])
fmt.Println("len:", len(a))

b := [5]int{1, 2, 3, 4, 5}
fmt.Println(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)

//切片
s := make([]string, 3)
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("get:", s[2])   // c
fmt.Println("len:", len(s)) // 3

s = append(s, "d")
s = append(s, "e", "f")
fmt.Println(s) // [a b c d e f]

c := make([]string, len(s))
copy(c, s)
fmt.Println(c) // [a b c d e f]

//map
m := make(map[string]int)
m["one"] = 1
m["two"] = 2
fmt.Println(m)           // map[one:1 two:2]
fmt.Println(len(m))      // 2
fmt.Println(m["one"])    // 1
fmt.Println(m["unknow"]) // 0

Go语言也支持自定义结构体, 通过type name struct{}

type user struct {
   name     string
   password string
}

支持指针

函数

func exists(m map[string]string, k string) (v string, ok bool) {
   v, ok = m[k]
   return v, ok
}

Go语言的函数定义如上所示, exists为函数名, 第一个括号内为入参, Go语言支持返回多个参数, 第二个括号内的v和ok均为回参

根据上述函数体, 该函数的作用是判断参数m所传入的map中是否存在k对应的值, 第二行的逻辑为当m中存在k时, v接受到k对应的值, ok的值为true; 如果不存在, ok的值为false, v为0.

在Golang里面可以为结构体定义结构体方法, 类似其他语言中的类成员方法

type user struct {
   name     string
   password string
}

func (u user) checkPassword(password string) bool {
   return u.password == password
}

通过这样定义, 用户可以使用a.checkPassword(xxxx)的方式来调用

其他

Go语言支持错误处理, 它的处理方式也更为简洁

通过众多标准库提供的函数方法, 实现字符串处理, 时间处理, json处理也是极为高效简洁

Go语言编程

猜数

字典

Socket5代理

学习资料

Go语言圣经(中文版)

参考材料

【后端专场 学习资料一】第五届字节跳动青训营