Go语言基础 | 青训营笔记

73 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 2 天

简介

这篇文章介绍我这几天学到的Go语言基本用法

关键字

目录

  1. import:导包
  2. package:声明程序所属的包
  3. var:定义变量
  4. const:设为常量
  5. type:定义类型
  6. struct:结构体
  7. inferface:接口
  8. func:函数或方法
  9. chan:管道(通道)
  10. map:基于key-value的数据结构
  11. go:开启协程
  12. for:循环
  13. range:遍历
  14. if:条件分支之一
  15. else:条件分支之一
  16. switch:条件语句
  17. select:条件语句
  18. case:条件分支之一
  19. return:返回
  20. goto:跳转
  21. fallthrough:在switch中强制执行后面的case代码
  22. break:退出循环(switch中不可用)
  23. default:switch的默认分支
  24. continue:跳过当前循环
  25. defer:延迟调用

用法

// 声明程序在main包下
package main

import (
   // 导格式化包(format)
   "fmt"
   "time"
)

// 主函数
func main() {
    
    // 等效于 var helloWorld = "hello world"
    // 或 helloWorld := "hello world" // 常用
    var helloWorld string = "hello world"
    // 调用fmt包暴露的函数Println(相当于调用了Java中用public修饰的方法)
    fmt.Println(helloWorld)
    
    // 开启协程,调用匿名函数,(5)中的()表示立即执行,5作为参数传递给i
    go func(i int) {
       fmt.Println(i)
    }(5)
    // 休眠1秒,减少主协程结束时上面的协程还没结束的概率
    time.Sleep(1)

    // 未完待续
}

内置变量类型

目录

  1. 常量:true、false、ioda、nil
  2. 无符号整型:uint、uint8、uint16、uint32、uint64、uintptr
  3. 浮点型:float32、float64、complex64、complex128
  4. 其他:bool、byte、string、error
  5. 函数:make、len、cap、new、appand、copy、close、delete、complex、real、imag、panic、recover

指针

指针变量指向基本类型

与C语言差异不大

s := "Go语言很好学"
p := &s // & 取地址
fmt.Println(*p) // *解引用

上述代码的输出结果是 Go语言很好学

指针变量指向结构体

和Java的相关用法比较相似

Go语言版本

type Student struct {
   name string
}

// 可以修改结构体成员属性的值
func (stu *Student) rename(newName string) {
   stu.name = newName
}

// 不可以修改结构体成员属性的值
func (stu Student) printlnName() {
   fmt.Println(stu.name)
}

main() {
    stu := &Student{
       name: "小敏",
    }
    stu.rename("小名")
    stu.printlnName()
}

Java语言版本

public class Student {
    protected String name;
    
    protected void rename(newName string) {
       name = newName;
    }
    
    protected void printlnName() {
       System.out.println(name);
    }
    
    public Student() {}
    
    public Student(String name) {
        this.name = name;
    }
    
    public static void main(String[] args) {
        Student stu = new Student("小敏");
        stu.rename("小名")
        stu.printlnName()
    }
}