GO语言基础入门指南 下篇 | 豆包MarsCode AI刷题

40 阅读5分钟

GO语言基础入门指南 下篇

一、控制流语句

  • 条件语句

  • if - else语句,例如:

a := 10
if a > 5 {
    fmt.Println("a is greater than 5")
} else {
    fmt.Println("a is less than or equal to 5")
}
  • switch语句,例如:
num := 2
switch num {
case 1:
    fmt.Println("The number is 1")
case 2:
    fmt.Println("The number is 2")
default:
    fmt.Println("The number is not 1 or 2")
}
  • 循环语句

    • for循环是 Go 语言中唯一的循环结构。基本形式是for init; condition; post { }。例如:
for i := 0; i < 5; i++ {
    fmt.Println(i)
}
  • 也可以省略initconditionpost部分,形成类似于while循环的形式。例如:

i := 0
for i < 5 {
    fmt.Println(i)
    i++
}
  • 还有一种无限循环的形式for { },可以在循环体内使用breakcontinue来控制循环的结束和跳过。

二、函数

  1. fmt 包中的函数
  • fmt.Println()

    • 功能:用于将数据输出到控制台,并在输出内容的末尾自动添加换行符。它可以接受多个参数,参数之间用逗号分隔,会按照顺序依次打印。
    • 示例
package main
import "fmt"
func main() {
    name := "Alice"
    age := 25
    fmt.Println("Name:", name, "Age:", age)
}

输出结果为:Name: Alice Age: 25

  • fmt.Printf()

    • 功能:按照指定的格式将数据输出到控制台。它使用格式化字符串来控制输出的格式。

    • 示例

package main
import "fmt"
func main() {
    pi := 3.14159
    fmt.Printf("The value of pi is approximately %.2f\n", pi)
}

输出结果为:The value of pi is approximately 3.14。其中%.2f是格式化字符串,表示将浮点数保留两位小数输出。

  • fmt.Scanln () 和 fmt.Scanf ()

    • 功能:用于从标准输入(例如用户在控制台输入)读取数据。fmt.Scanln会读取用户输入的一行内容,并按照空格或换行符来分割数据,将其赋值给相应的变量;fmt.Scanf则按照指定的格式来读取输入数据。
    • 示例(fmt.Scanln)
package main
import "fmt"
func main() {
    var name string
    var age int
    fmt.Println("Please enter your name and age:")
    fmt.Scanln(&name, &age)
    fmt.Printf("Your name is %s and you are %d years old.\n", name, age)
}

当用户在控制台输入Bob 30并回车后,程序会将Bob赋值给name30赋值给age

  • 示例(fmt.Scanf)

package main
import "fmt"
func main() {
    var width, height int
    fmt.Println("Please enter the width and height in the format 'width height':")
    fmt.Scanf("%d %d", &width, &height)
    area := width * height
    fmt.Printf("The area is %d\n", area)
}

如果用户输入5 6,程序会按照%d %d的格式读取,将5赋值给width6赋值给height,然后计算并输出面积。
2. strings 包中的函数

  • strings.Contains()

    • 功能:用于检查一个字符串是否包含另一个字符串。
    • 示例
package main
import (
    "fmt"
    "strings"
)
func main() {
    text := "Hello, world!"
    sub := "world"
    if strings.Contains(text, sub) {
        fmt.Printf("The string '%s' contains '%s'\n", text, sub)
    } else {
        fmt.Printf("The string '%s' does not contain '%s'\n", text, sub)
    }
}

输出结果为:The string 'Hello, world!' contains 'world'

  • strings.Split()

    • 功能:将一个字符串按照指定的分隔符分割成多个子字符串,并返回一个切片。
    • 示例
package main
import (
    "fmt"
    "strings"
)
func main() {
    text := "apple,banana,cherry"
    fruits := strings.Split(text, ",")
    fmt.Println(fruits)
}

输出结果为:[apple banana cherry],即将字符串按照逗号分割成了一个包含三个字符串的切片。

  • strings.Join()

    • 功能:与strings.Split相反,它将一个字符串切片按照指定的分隔符连接成一个字符串。
    • 示例
package main
import (
    "fmt"
    "strings"
)
func main() {
    fruits := []string{"apple", "banana", "cherry"}
    joined := strings.Join(fruits, " and ")
    fmt.Println(joined)
}

输出结果为:apple and banana and cherry,即将切片中的字符串用and连接成了一个字符串。
3. math 包中的函数

  • math.Abs()

    • 功能:用于计算一个数的绝对值。它可以接受整数或浮点数作为参数。
    • 示例
package main
import (
    "fmt"
    "math"
)
func main() {
    num := -5.5
    absValue := math.Abs(num)
    fmt.Println(absValue)
}

输出结果为:5.5

  • math.Sqrt()

    • 功能:用于计算一个非负数的平方根。
    • 示例
package main
import (
    "fmt"
    "math"
)
func main() {
    num := 9.0
    squareRoot := math.Sqrt(num)
    fmt.Println(squareRoot)
}

输出结果为:3

  • math.Max () 和 math.Min ()

    • 功能math.Max用于返回两个数中的最大值,math.Min用于返回两个数中的最小值。它们可以接受整数或浮点数作为参数。
    • 示例(math.Max)
package main
import (
    "fmt"
    "math"
)
func main() {
    a := 10
    b := 20
    maxValue := math.Max(a, b)
    fmt.Println(maxValue)
}

输出结果为:20

  • 示例(math.Min)
package main
import (
    "fmt"
    "math"
)
func main() {
    a := 5.5
    b := 3.3
    minValue := math.Min(a, b)
    fmt.Println(minValue)
}

输出结果为:3.3
4. strconv 包中的函数

  • strconv.Itoa()

    • 功能:将整数转换为字符串。
    • 示例
package main
import (
    "fmt"
    "strconv"
)
func main() {
    num := 123
    str := strconv.Itoa(num)
    fmt.Printf("The string representation of %d is %s\n", num, str)
}

输出结果为:The string representation of 123 is 123

  • strconv.Atoi()

    • 功能:将字符串转换为整数。如果转换失败,会返回一个错误。
    • 示例
package main
import (
    "fmt"
    "strconv"
)
func main() {
    str := "456"
    num, err := strconv.Atoi(str)
    if err == nil {
        fmt.Printf("The integer representation of %s is %d\n", str, num)
    } else {
        fmt.Println("Conversion error:", err)
    }
}

输出结果为:The integer representation of 456 is 456

三、包(Packages)

  1. 创建和使用包

    • 创建包:在 Go 语言中,一个文件夹可以看作是一个包。例如,在my_package文件夹下创建一个myfunc.go文件,文件开头写package my_package,这里定义了一个名为my_package的包。
    • 使用包:在其他文件中使用这个包时,需要先导入。例如,在main.go文件中,如果要使用my_package中的函数,需要在文件开头写import "my_package"(假设my_packageGOPATH或者Go Modules管理的路径下),然后就可以调用包中的函数。
  2. Go Modules

    • Go Modules 是 Go 语言用于管理依赖包的工具。可以在项目目录下使用go mod init [module name]命令初始化一个模块,例如go mod init my_project。之后,当你在项目中引入其他依赖包时,Go Modules 会自动下载并管理这些包的版本。