Golang基础——2

发布于 2021-11-06  0 次阅读


结构体

属性和函数的结合体,就像抽象类一样

目录结构

├─index
│ └─index.go
└─main.go

main.go
______________________________________________________________________
package main

import (
	"fmt"
	"./index"
)

func main() {
	//dog 结构体
	index.TestStruct()
//dog : {{1} a1 0 c1}

	var dog index.Dog
	dog.Name = "son"
	dog.Color = "s1"
	dog.Id = 5

	//Run 首字母大小写控制作用域
	dog.Run()
	dog.Eat()
	dog.Play()
//dog name : son  dog is running
//dog color : s1  dog is running
//animal id : 5  animal is running

}
index.go
______________________________________________________________________
package index

import (
	"fmt"
)

//组合实现继承
//Animal可以理解为父类
type Animal struct {
	Id  int
}

type Dog struct {
	Animal
	Name  string
	Age   int
	Color string
}

func TestStruct() {
	//方法1
	var dog Dog
	dog.Name = "a1"
	dog.Color = "c1"
	dog.Id = 1

	//方法2
	//dog := Dog{Color:"c2", Name:"a2", Age:22}

	//方法3
	//dog := new(Dog)
	//dog.Age = 43
	//dog.Name = "dsdg"

	fmt.Println("dog :", dog)
}

//首字母大小写控制作用域|小写只能作用package内
func (a *Animal) Play() {
	fmt.Println("animal id :", a.Id, " animal is running")
}

func (d *Dog) Run() {
	fmt.Println("dog name :", d.Name, " dog is running")
}

func (d *Dog) Eat() {
	fmt.Println("dog color :", d.Color, " dog is running")
}

接口

隐式实现

...待续

君子慎独,不欺暗室。卑以自牧,含章可贞。
最后更新于 2021-11-06