这是我参与「第五届青训营 」伴学笔记创作活动的第 2 天
简介
这篇文章介绍我这几天学到的Go语言基本用法
关键字
目录
- import:导包
- package:声明程序所属的包
- var:定义变量
- const:设为常量
- type:定义类型
- struct:结构体
- inferface:接口
- func:函数或方法
- chan:管道(通道)
- map:基于key-value的数据结构
- go:开启协程
- for:循环
- range:遍历
- if:条件分支之一
- else:条件分支之一
- switch:条件语句
- select:条件语句
- case:条件分支之一
- return:返回
- goto:跳转
- fallthrough:在switch中强制执行后面的case代码
- break:退出循环(switch中不可用)
- default:switch的默认分支
- continue:跳过当前循环
- 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)
// 未完待续
}
内置变量类型
目录
- 常量:true、false、ioda、nil
- 无符号整型:uint、uint8、uint16、uint32、uint64、uintptr
- 浮点型:float32、float64、complex64、complex128
- 其他:bool、byte、string、error
- 函数: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()
}
}