Go (Golang)语言(课外基础篇)| 青训营

116 阅读4分钟

此文章将概括学习Go语言基础中关于Terminal Command, Code(Package declaration & usage, Values & Variables)的知识以及fmt package和Function中的知识点及重点

Terminal Command

在每次写完代码之后,我们都需要使用command line来对文件进行build, execute, compiles & run, 这里概括出三种command line来方便我们使用,在这里我们假设有main.go这个文件并对其进行操作。

  • build file: go build main.go
  • execute file: ./main
  • compiles & run:

值得注意的是,execute文件之前,需要提前对文件进行compile,当Go编译了main.go的文件以后,才可以用./main来运行文件。 此外,go run main.go命令可以对文件进行编译并运行,但不会build,也就是说,在编译并运行前需要对文件进行build方可跑动改后的代码。

Code

!!只有带有package main 声明\textcolor{red}{\text{package main 声明}}的package将编译成可执行文件!!
一切都始于Hello World, Go 语言也不例外,让我来看最经典的Hello World在Go语言中如何写出来的。

package main

import "fmt" //导入fmt包

func main(){
  fmt.Println("Hello World")
}

从这个example,我们可见仅用几行代码编写出hello world的小程式,能看出Go语言的简洁便利。接下来让我们逐步拆解每行代码并一点点介绍里面的知识点。

package main,正如这一个section开头所提到的,package main声明了这个package内的文件会被编译成可执行文件,我们所有的code file都将使用这个开头,表示我(当前这个文件)属于main package的。

import "fmt"这一行导入了fmt包,fmt包内包含了输入输出,string编辑等基础交互功能,这个包的详细内容会在后面提到。

导入包有两种方式:
方式一:逐行逐包导入

import "package1"
import "package2"

方式二:一起导入

import (
  "package1"
  "package2"
)

在此方法下所有包都可放到括号里一起导入。此外我们还可以给导入的package加alias name比如我们想在后面的code中少写一些package1.function(), 我们可以加alias name, 将package1变成p1从而减少代码量,代码如下:

import (
  p1 "package1"
  "package2"
)

注释

注释跟Java相同,如需comment out单行,或在代码后加注释,可用”//“来表示,后面跟注释内容。
若需要comment out多行代码,可用“/* */”来注释。
快捷键tips: 在大多IDE中,可直接括住多行代码用 ‘cmd’+‘/’ (mac)或 ‘ctrl’+‘/’来注释掉。

Values & Variables

Go中常见的variable和constant的type大致有int, float, string, bool, 以及complex,在int,float,和complex中又分成多种不同的type。以int为例,它包括8位,16位,32位,64位,signed, unsigned区别,根据不同的取值范围可以去选择不同的type。下图[1]表现了int中8种不同type,所占memory空间及他们取值范围:

image.png

Literal:

Go内常见运算符大致有以下五种:

  • + to add
  • - to subtract
  • * to multiply
  • / to divide
  • % to take the remainder (the modulus operator) between two numbers.
Constant:

Go中若我们需要一个常量,我们可以用const关键词来建立一个常量,并立刻给这个constant赋值。 use “const” keyword to create a constant, assign a value immediately to the constant.

e.g.

const earthsGravity = 9.80665

or

const funFact = "Hummingbirds' wings can beat up to 200 times a second."
Variable:

与constant相似,但value可以在程序运行时更改,keyword:“var”。declare的格式为:
var variable_name var_type.

declaration example:

var lengthOfSong uint16
var isMusicOver bool
var songRating float32
Inferring type

此外,variable有一种简便declare的方式。

by using := declaration, we don’t need state its type. Directly apply := operator if we know the value.

Go会自动匹配和value对应的type。

example:

nuclearMeltdownOccurring := true
radiumInGroundWater := 4.521
daysSinceLastWorkplaceCatastrophe := 0
externalMessage := "Everything is normal. Keep calm and carry on."
Multiple Variable Declaration

在go中,我们可以同时define多个variable,用传统格式或inferring都可以。若用inferring,variable的type类型可以不同。

var part1, part2 string //initialize two strings called part1, part2

//variables are not necessarily to be the same type
quote, fact := "Bears, Beets, Battlestar Galactica", true 

fmt package

fmt最常见的应用地方就是输入输出,以及struct string。

输出
  • 打印单行(arguement间自动留空间):fmt.Println() //和Java的System.out.println一致
  • 只print(不留空间不换行):fmt.Print() //和Java中System.out.print一致
  • 插入string或在string中保留placeholder并使用值填充placeholder: fmt.Printf()
placeholders
  • %v -> verbs (the value in a default format)
  • %T -> prints out the type of the variables
  • %d -> interpolate a number into a string
  • %f -> we can limit how precise we are by including a value between the % and f. e.g. %.2f : precise to 2 decimal places.
Sprintln & Sprint —— Struct a string

构造一个字符串,与 Println 和 Printf 相同 Println 自动在参数之间包含空格,而 Sprint 则不会。 e.g.

step1 := "Breathe in..."
step2 := "Breathe out..."
meditation := fmt.Sprintln(step1,step2)
fmt.Println(meditation) //Print Breathe in... Breathe out...

Sprintf: 结合Sprint和printf, 可以用verbs以及placeholders构造一个string.

输入

Getting User Input — fmt.Scan
与C中scan类似。!! variable前面要加&, 表示address!!
e.g.

var food string
fmt.Scan(&food)
fmt.Printf("Sure, we can have %v for lunch.", food)

Function

在每个自定义函数中,我们应该在大括号前添加返回类型, 每个函数可以返回多个值.

e.g.

func GPA(midtermGrade float32, finalGrade float32) (string, float32){
}
deferring resolution

通过使用 defer 关键字,我们可以将函数调用延迟到当前函数的末尾。 这对于日志记录、文件写入和其他实用程序很有用.

此外,Go保留了C中的指针特性,我们也可以在Go中使用与C中相同的pointer和address概念。

Reference:

[1] “Learn Go,” Codecademy, www.codecademy.com/courses/lea… (accessed Jul. 28, 2023).