package main
import (
"fmt"
"os"
)
func init() {
// 每个包中第一个执行的函数,import时自动执行,不能被用户调用
// 没有参数,没有返回值
// 包中包含多个init时,调用顺序不确定
fmt.Println("Hello Init")
}
func main() {
//switchTest()
//gotoTest()
//enumTest()
//structTest()
p1 := Person{name: "小明", age: 10, gender: "男"}
p1.Eat()
fmt.Println(p1.name)
s1 := Student{
p: Person{
name: "小新",
age: 12,
gender: "男",
},
score: 100,
school: "实验一小",
}
fmt.Println(s1)
t1 := Teacher{}
t1.name = "周老师"
t1.subject = "Python"
t1.age = 40
t1.gender = "男"
fmt.Println(t1)
}
func interfaceTest() {
// 接口可以接收任意类型的数据
array := make([]interface{}, 3)
array[0] = 1
array[1] = "hello world!"
array[2] = true
}
type Person struct {
// 成员属性
name string
age uint8
gender string
}
type Student struct {
// 类的嵌套
p Person
school string
score float32
}
type Teacher struct {
// 类的继承
Person
subject string
}
func (p *Person) Eat() {
// 使用指针可以修改属性值,无指针无法修改属性值
fmt.Println(p.name + "在吃东西!")
p.name = "Tom"
}
func deferTest() {
// 延迟关键字,确保语句在当前栈退出时执行
// lock.Lock()
// defer lock.Unlock()
}
func structTest() {
p := Person{name: "zj", age: 18, gender: "M"}
fmt.Println(p)
}
func enumTest() {
const (
_ = iota
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
)
fmt.Println(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
}
func gotoTest() {
s := 0
// LAB 标签
// goto Lab 下次进入时,不记录循环内的数据
// continue Lab 下次进入时,记录循环内的数据
// break Lab 直接跳出指定位置
LAB1:
s += 1
for i := 1; i < 10; i++ {
for j := 1; j <= i; j++ {
fmt.Print(i, "x", j, "=", i*j, " ")
}
fmt.Println()
}
if s < 3 {
goto LAB1
}
}
func switchTest() {
cmds := os.Args
for key, cmd := range cmds {
fmt.Println(key, cmd)
}
// golang中的switch默认自带break
switch cmds[1] {
case "-a":
fmt.Println("all")
// 关键字fallthrough可以向下穿透
fallthrough
case "-b":
fmt.Println("boss")
case "-c":
fmt.Println("Class")
default:
fmt.Println("No command")
}
}
Go基础语法练习(2)
775 views