• Go 语言基础语法 3


    Go 语言是一种静态类型的编程语言,具有简洁、可靠、高效的特点。下面是 Go 语言的基础语法,包括变量、数据类型、控制结构、函数、字符串、数组和切片、指针、结构体、接口、错误处理和并发编程等。

    变量

    Go 语言中,可以使用 var 语句声明变量。例如:

    1. var x int
    2. x = 10

    也可以使用 short variable declarations 语句声明变量。例如:

    x := 10
    

    Go 语言中,还有许多内置的变量类型,例如 intfloatboolstring 等。

    数据类型

    Go 语言中,有许多内置的数据类型,例如:

    • int:整数类型
    • float:浮点数类型
    • bool:布尔类型
    • string:字符串类型
    • byte:字节类型
    • rune: Unicode 字符类型
    • complex:复数类型
    • imag:虚数类型

    控制结构

    Go 语言中,有以下几种控制结构:

    • if 语句:if x > 0 { ... }
    • for 语句:for i := 0; i < 5; i++ { ... }
    • switch 语句:switch x { case 1: ... case 2: ... }
    • goto 语句:goto LABEL

    函数

    Go 语言中,可以使用 func 语句声明函数。例如:

    1. func add(x int, y int) int {
    2. return x + y
    3. }

    函数可以返回多个值,例如:

    1. func add(x int, y int) (int, int) {
    2. return x + y, x - y
    3. }

    字符串

    Go 语言中,可以使用 string 语句声明字符串。例如:

    str := "hello world"
    

    字符串可以使用 + 运算符连接,例如:

    str := "hello " + "world"
    

    字符串可以使用 fmt.Sprintf 函数格式化,例如:

    str := fmt.Sprintf("hello %s", "world")
    

    数组和切片

    Go 语言中,可以使用 [] 语句声明数组和切片。例如:

    arr := [5]int{1, 2, 3, 4, 5}
    

    数组和切片可以使用索引访问,例如:

    arr[0] = 10
    

    数组和切片可以使用 len 函数获取长度,例如:

    len(arr)
    

    指针

    Go 语言中,可以使用 * 语句声明指针。例如:

    p := &x
    

    指针可以使用 * 运算符解引用,例如:

    *p = 10
    

    结构体

    Go 语言中,可以使用 struct 语句声明结构体。例如:

    1. type Person struct {
    2. name string
    3. age int
    4. }

    结构体可以使用点号访问字段,例如:

    1. p := Person{"John", 30}
    2. p.name = "Jane"

    接口

    Go 语言中,可以使用 interface 语句声明接口。例如:

    1. type Printer interface {
    2. Print()
    3. }

    接口可以实现多个方法,例如:

    1. type Logger struct{}
    2. func (l Logger) Print() {
    3. fmt.Println("log")
    4. }

    错误处理

    Go 语言中,可以使用 error 语句声明错误。例如:

    1. type error interface {
    2. Error() string
    3. }

    错误可以使用 if 语句处理,例如:

    1. if err != nil {
    2. fmt.Println(err)
    3. }

    并发编程

    Go 语言中,可以使用 go 语句声明 goroutine。例如:

    1. go func() {
    2. fmt.Println("hello")
    3. }()

    goroutine 可以使用 channel 语句通信,例如:

    1. ch := make(chan int)
    2. go func() {
    3. ch <- 10
    4. }()

    goroutine 可以使用 sync 语句同步,例如

    1. mu := &sync.Mutex{}
    2. go func() {
    3. mu.Lock()
    4. fmt.Println("hello")
    5. mu.Unlock()
    6. }()
  • 相关阅读:
    jinfo_动态调整JVM参数(无需重启)(实践)
    Linux--安装部署Docker
    spring6使用启用Log4j2日志框架
    操作符keyof的作用是什么
    linux-硬盘
    Spring Bean 的生命周期(看着图不迷路)
    Yaml语法学习
    数据结构与算法-砖墙问题
    python爬虫概述及简单实践:获取豆瓣电影排行榜
    Python 爬虫实战之爬淘宝商品并做数据分析
  • 原文地址:https://blog.csdn.net/qq_40698086/article/details/140920803