Golang基础-Basics

Packages

Go语言中的包和其他语言的库或模块的概念类似,目的都是为了支持模块化、封装、单独编译和代码重用。一个包的源代码保存在一个或多个以.go为文件后缀名的源文件中,通常一个包所在目录路径的后缀是包的导入路径;例如包gopl.io/ch1/helloworld对应的目录路径是 $GOPATH/src/gopl.io/ch1/helloworld。
每个包都对应一个独立的名字空间。例如,在image包中的Decode函数和在unicode/utf16包 中的Decode函数是不同的。要在外部引用该函数,必须显式使用image.Decode或 utf16.Decode形式访问。
包还可以让我们通过控制哪些名字是外部可见的来隐藏内部实现信息。在Go语言中,一个简单的规则是:如果一个名字是大写字母开头的,那么该名字是导出的(译注:因为汉字不区分大小写,因此汉字开头的名字是没有导出的)。
引入自己写的包的流程:

  1. 打开 GO111MODULE="on"
  2. 在目录下运行 go mod init moduleName
  3. 在目录下运行 go mod tidy
  4. import "moduleName/packagePath"

包内的函数名首字母要大写才能被别的包调用。结构体内的成员也是大写才是公有的,可见的

Variables

var explicit int // Explicitly typed
implicit := 10   // Implicitly typed as an int
count := 1 // Assign initial value
count = 2  // Update to new value
count = false // This throws a compiler error due to assigning a non `int` type

Constants

常量表达式的值在编译期计算,而不是在运行期。每种常量的潜在类型都是基础类型:boolean、string或数字。
一个常量的声明语句定义了常量的名字,和变量的声明语法类似,常量的值不可修改,这样可以防止在运行期被意外或恶意的修改。
一个常量的声明也可以包含一个类型和一个值,但是如果没有显式指明类型,那么将从右边的表达式推断类型。
为什么const不用:=赋值?思考变量:=和=的区别,一个是首次声明和赋初值,另一个是更改值。但是const不能更改,所以只需要=就可以了。

const Age = 21 // Defines a numeric constant 'Age' with the value of 21
const (
    e = 2.71828182845904523536028747135266249775724709369995957496696763
    pi = 3.14159265358979323846264338327950288419716939937510582097494459
)
const noDelay time.Duration = 0

Functions

函数声明包括函数名、形式参数列表、返回值列表(可省略)以及函数体。
返回值列表可以是只说明返回值类型,也可以是指明返回值变量名,这样只需写一个return,即Naked Return。

func name(parameter-list) (result-list) {
    body
}

Exercise

package lasagna

// TODO: define the 'OvenTime' constant
const OvenTime = 40

// RemainingOvenTime returns the remaining minutes based on the `actual` minutes already in the oven.
func RemainingOvenTime(actualMinutesInOven int) int {
    return OvenTime - actualMinutesInOven
}

// PreparationTime calculates the time needed to prepare the lasagna based on the amount of layers.
func PreparationTime(numberOfLayers int) int {
    return 2 * numberOfLayers
}

// ElapsedTime calculates the time elapsed cooking the lasagna. This time includes the preparation time and the time the lasagna is baking in the oven.
func ElapsedTime(numberOfLayers, actualMinutesInOven int) int {
    return 2*numberOfLayers + actualMinutesInOven
}
posted @ 2023-02-18 13:01  roadwide  阅读(20)  评论(0编辑  收藏  举报