• Go语句与表达式深度解析:全案例手册


    关注公众号【TechLeadCloud】,分享互联网架构、云服务技术的全维度知识。作者拥有10+年互联网服务架构、AI产品研发经验、团队管理经验,同济本复旦硕,复旦机器人智能实验室成员,阿里云认证的资深架构师,项目管理专业人士,上亿营收AI产品研发负责人。

    file

    语句

    语句是Go编程语言中完成特定操作的单个逻辑指令。语句是组成程序的基本单元,它们可以控制程序流程、进行赋值、声明变量等。

    1. 声明语句

    1.1 变量声明

    用于定义一个或多个变量,但不一定要赋值。

    举例

    var age int
    var name, address string
    
    • 1
    • 2

    1.2 常量声明

    定义一个或多个常量值。

    举例

    const PI = 3.14
    const greeting = "Hello, Go!"
    
    • 1
    • 2

    2. 赋值语句

    用于给已声明的变量分配新的值。

    举例

    x := 10
    y = x + 5
    a, b := 20, 30
    
    • 1
    • 2
    • 3

    3. 控制流语句

    3.1 条件语句

    if语句

    基于某个条件来执行代码块。

    举例

    if x > y {
        fmt.Println("x is greater than y")
    } else if x < y {
        fmt.Println("x is less than y")
    } else {
        fmt.Println("x is equal to y")
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    switch语句

    基于一个表达式或值来执行多个代码块中的一个。

    举例

    switch grade {
    case "A":
        fmt.Println("Excellent!")
    case "B":
        fmt.Println("Good")
    default:
        fmt.Println("Passed")
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3.2 循环语句

    for语句

    用于重复执行某段代码。

    举例

    for i := 0; i < 10; i++ {
        fmt.Println(i)
    }
    
    for _, value := range array {
        fmt.Println(value)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3.3 跳转语句

    break语句

    用于中断当前循环。

    举例

    for i := 0; i < 10; i++ {
        if i == 5 {
            break
        }
        fmt.Println(i)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    continue语句

    跳过当前迭代,并继续下一个迭代。

    举例

    for i := 0; i < 10; i++ {
        if i%2 == 0 {
            continue
        }
        fmt.Println(i)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    return语句

    从函数中返回特定值。

    举例

    func add(a int, b int) int {
        return a + b
    }
    
    • 1
    • 2
    • 3
    goto语句

    跳转到指定的标签。

    举例

    for i := 0; i < 10; i++ {
        if i == 5 {
            goto end
        }
        fmt.Println(i)
    end:
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    4. 其他语句

    4.1 defer语句

    确保在函数结束前执行某个语句。

    举例

    func printFile() {
        file, err := os.Open("file.txt")
        if err != nil {
            panic(err)
        }
        defer file.Close()
        
        // Do file operations...
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    4.2 go语句

    在新的goroutine中执行函数调用。

    举例

    go func() {
        fmt.Println("Executing in a new goroutine")
    }()
    
    • 1
    • 2
    • 3

    实战案例

    语句语句样例
    变量声明var age intvar name, address stringvar x, y int = 3, 4var active boolvar salary = 50000
    常量声明const PI = 3.14const greeting = "Hello, Go!"const active = falseconst daysInWeek = 7const lightSpeed = 299792458
    赋值语句x := 10y = x + 5a, b := 20, 30name = "Alice"isActive := true
    if语句if x > 10 { ... }if x > 10 && y < 5 { ... }if active { ... }if name := getName(); name != "" { ... }if age > 18 { ... } else { ... }
    switch语句switch x { ... }switch { case x > 10: ... }switch day { case "Monday": ... }switch n := 4; n { ... }switch y.(type) { ... }
    for语句for i := 0; i < 5; i++ { ... }for i, v := range arr { ... }for x > 5 { ... }for key, val := range mapData { ... }for _, char := range str { ... }
    break语句for { if condition { break } }switch { case x: if y { break } }for x > 10 { ...; break; ... }label: for { ...; break label; ... }for i := 0; i < 10; i++ { if i == 5 { break } }
    continue语句for i := 0; i < 10; i++ { if i%2 == 0 { continue } }for _, v := range data { if v == nil { continue } }for x > 0 { ...; if condition { continue } ... }for { if !isValid(data) { continue } ... }for idx, value := range items { if value == "" { continue } }
    return语句func add(a, b int) int { return a + b }func name() string { return "Alice" }func getDetails() (string, int) { return "Alice", 30 }func isActive() bool { ...; return false }func calculate() float64 { ...; return result }
    goto语句label1: for { ...; if x > 5 { goto label1 } }label2: fmt.Println("Start"); ...; goto label2if condition { goto errorHandling } ... errorHandling: ...if !isValid { goto cleanup } ... cleanup: ...
    defer语句file, _ := os.Open("file.txt"); defer file.Close()mutex.Lock(); defer mutex.Unlock()defer fmt.Println("Finished!")conn.Connect(); defer conn.Disconnect()reader := openReader(); defer reader.Close()
    go语句go fmt.Println("Running in goroutine")go process(data)go func(val int) { ... }(x)go startServer()go handleRequest(request)

    表达式介绍、详解、举例

    在编程中,表达式是一个结构,通过某种方式组合了变量、常量和操作符,并且可以被评估为某个值。在Go中,表达式根据所包含的内容和结果的不同,可以有多种形式。

    1. 基础表达式

    1.1 字面量

    字面量是一个表示固定值的表达式。

    举例

    42       // 整型字面量
    3.14     // 浮点字面量
    true     // 布尔字面量
    "Hello"  // 字符串字面量
    
    • 1
    • 2
    • 3
    • 4

    1.2 变量和常量

    变量和常量是预先定义的,具有特定名称和值的实体。

    举例

    const PI = 3.14
    var name = "Go"
    
    • 1
    • 2

    2. 复合表达式

    2.1 算术表达式

    这些表达式使用算术运算符,如+-*/%

    举例

    a := 5
    b := 2
    sum := a + b        // 结果:7
    difference := a - b // 结果:3
    product := a * b    // 结果:10
    quotient := a / b   // 结果:2
    remainder := a % b  // 结果:1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2.2 关系表达式

    关系表达式评估为布尔值,常用的关系运算符有==!=<<=>>=

    举例

    x := 5
    y := 3
    result1 := x == y  // 结果:false
    result2 := x > y   // 结果:true
    
    • 1
    • 2
    • 3
    • 4

    2.3 逻辑表达式

    逻辑表达式用于组合多个布尔表达式,常用的逻辑运算符有&&||!

    举例

    a := true
    b := false
    result1 := a && b  // 结果:false
    result2 := a || b  // 结果:true
    result3 := !a     // 结果:false
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.4 赋值表达式

    赋值表达式给变量赋值,并返回该值。

    举例

    x := 10           // 使用 := 进行赋值
    y = x + 5         // 使用 = 进行赋值
    
    • 1
    • 2

    3. 函数调用表达式

    函数调用返回函数的返回值。

    举例

    func add(a int, b int) int {
        return a + b
    }
    
    result := add(5, 3)  // 结果:8
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4. 类型转换表达式

    这些表达式将值从一个类型转换为另一个类型。

    举例

    x := 5.8
    y := int(x)  // 结果:5
    
    • 1
    • 2

    实战案例

    语句语句样例
    变量声明var age intvar name, address stringvar x, y int = 3, 4var active boolvar salary = 50000
    常量声明const PI = 3.14const greeting = "Hello, Go!"const active = falseconst daysInWeek = 7const lightSpeed = 299792458
    赋值语句x := 10y = x + 5a, b := 20, 30name = "Alice"isActive := true
    if语句if x > 10 { ... }if x > 10 && y < 5 { ... }if active { ... }if name := getName(); name != "" { ... }if age > 18 { ... } else { ... }
    switch语句switch x { ... }switch { case x > 10: ... }switch day { case "Monday": ... }switch n := 4; n { ... }switch y.(type) { ... }
    for语句for i := 0; i < 5; i++ { ... }for i, v := range arr { ... }for x > 5 { ... }for key, val := range mapData { ... }for _, char := range str { ... }
    break语句for { if condition { break } }switch { case x: if y { break } }for x > 10 { ...; break; ... }label: for { ...; break label; ... }for i := 0; i < 10; i++ { if i == 5 { break } }
    continue语句for i := 0; i < 10; i++ { if i%2 == 0 { continue } }for _, v := range data { if v == nil { continue } }for x > 0 { ...; if condition { continue } ... }for { if !isValid(data) { continue } ... }for idx, value := range items { if value == "" { continue } }
    return语句func add(a, b int) int { return a + b }func name() string { return "Alice" }func getDetails() (string, int) { return "Alice", 30 }func isActive() bool { ...; return false }func calculate() float64 { ...; return result }
    goto语句label1: for { ...; if x > 5 { goto label1 } }label2: fmt.Println("Start"); ...; goto label2if condition { goto errorHandling } ... errorHandling: ...if !isValid { goto cleanup } ... cleanup: ...
    defer语句file, _ := os.Open("file.txt"); defer file.Close()mutex.Lock(); defer mutex.Unlock()defer fmt.Println("Finished!")conn.Connect(); defer conn.Disconnect()reader := openReader(); defer reader.Close()
    go语句go fmt.Println("Running in goroutine")go process(data)go func(val int) { ... }(x)go startServer()go handleRequest(request)

    关注公众号【TechLeadCloud】,分享互联网架构、云服务技术的全维度知识。作者拥有10+年互联网服务架构、AI产品研发经验、团队管理经验,同济本复旦硕,复旦机器人智能实验室成员,阿里云认证的资深架构师,项目管理专业人士,上亿营收AI产品研发负责人。

    file

  • 相关阅读:
    一、路由基础
    BERT预训练模型系列总结
    synchronized锁范围
    2023Q2全球可穿戴腕带出货量达 4400 万台
    嵌入式linux相机 框图
    vue学习笔记23-组件事件⭐
    软件设计模式学习笔记(七)
    DP 优化方法合集
    实现堆的各种基本运算的算法(数据结构)
    Eureka 高可用
  • 原文地址:https://blog.csdn.net/magicyangjay111/article/details/133742552