1.变量的多行定义
var (
aa int = 10
bb string = "zzs"
cc bool = false
dd float32 = 3.14
)
fmt.Printf("aa:%d,bb:%s,cc:%t,dd:%f", aa, bb, cc, dd)
2.iota知识点
- 测试代码
const (
BEIJING = iota
SHANGHAI
TIANJIN
)
const (
a = 10 * iota
b
c
)
const (
aa, bb = 1 + iota, 2 + iota //iota = 0
cc, dd //iota = 1
ee, ff = 2 * iota, 3 * iota //iota = 2
gg, hh
)
func main() {
fmt.Println(BEIJING)
fmt.Println(SHANGHAI)
fmt.Println(TIANJIN)
fmt.Println("=============")
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println("=============")
fmt.Println(aa)
fmt.Println(bb)
fmt.Println(cc)
fmt.Println(dd)
fmt.Println(ee)
fmt.Println(ff)
fmt.Println(gg)
fmt.Println(hh)
}
- 运行结果
3.Import导包路径问题与Init方法
- Import导包路径问题
4.Import匿名及别名导包
5.slice切片截取
- 测试代码
切片是引用传递,就算从其它切片中截取出来一段,对其进行改变同时也会改变原始切片
使用copy函数可以对其进行深拷贝
func main() {
arr := []int{1, 2, 3, 4, 5}
arr1 := arr[2:4]
arr1[0] = 999
fmt.Println(arr[0])
fmt.Println(arr1[0])
fmt.Printf("%p\n", arr)
fmt.Printf("%p\n", arr1)
arr2 := make([]int, len(arr))
copy(arr2, arr)
fmt.Println(arr2)
}
面向对象(继承)
type Human struct {
name string
sex bool
}
func (h *Human) Eat() {
fmt.Println("Eat...")
}
type SuperMain struct {
Human
level int
}
func (s *SuperMain) Eat() {
fmt.Println("superEat...")
}
func (s *SuperMain) Sleep() {
fmt.Println("superSleep...")
}
func main() {
s := &SuperMain{
Human: Human{
name: "zzs",
sex: true,
},
level: 10,
}
s.Eat()
s.Sleep()
}
面向对象(多态)
type Animal interface {
Eat()
Sleep()
Play()
}
type Cat struct {
}
func (c *Cat) Eat() {
fmt.Println("Cat Eat...")
}
func (c *Cat) Sleep() {
fmt.Println("Cat Sleep...")
}
func (c *Cat) Play() {
fmt.Println("Cat Play...")
}
type Dog struct {
}
func (d *Dog) Eat() {
fmt.Println("Dog Eat...")
}
func (d *Dog) Sleep() {
fmt.Println("Dog Sleep...")
}
func (d *Dog) Play() {
fmt.Println("Dog Play...")
}
func main() {
var animal Animal
animal = &Cat{}
animal.Eat()
animal.Sleep()
animal.Play()
animal = &Dog{}
animal.Eat()
animal.Sleep()
animal.Play()
AnimalToDo(&Cat{})
AnimalToDo(&Dog{})
}
func AnimalToDo(a Animal) {
a.Eat()
a.Sleep()
a.Play()
}
变量的pair结构
golang中的所有变量都有个pair<type,value>
type Reader interface {
ReadBook()
}
type Writer interface {
WriteBook()
}
type Book struct {
}
func (b *Book) ReadBook() {
fmt.Println("Read Book ...")
}
func (b *Book) WriteBook() {
fmt.Println("Write Book ...")
}
func main() {
// b: pair<type:*Book,value:book{}地址>
b := &Book{}
var r Reader
// r: pair<type:*Book,value:book{}地址>
r = b
r.ReadBook()
var w Writer
// w: pair<type:*Book,value:book{}地址>
w = r.(Writer) //此处为什么会断言成功,因为w,r具体的type一致
w.WriteBook()
}