go基础 面向对象

47 阅读2分钟

基础

package main

import "fmt"

//  类
type Hero struct {
	//  如果属性字母大写,外包可以直接访问,否则需要通过方法访问
	Name  string
	Age   int
	Level int
}

func (c Hero) Show() {
	fmt.Println("hero =", c)
}

func (c Hero) GetName() string {
	return c.Name
}

//  无法改变 c 的值 传递的是副本
func (c Hero) SetName(name string) {
	c.Name = name
}
func (c *Hero) SetName2(name string) {
	c.Name = name
}

func main() {

	hero := Hero{
		Name:  "adekang",
		Age:   18,
		Level: 1,
	}

	hero.Show() // hero = {adekang 18 1}
	hero.SetName("adekang2")
	res := hero.GetName()
	fmt.Println(res) // adekang

	hero.SetName2("tom")
	res = hero.GetName()
	fmt.Println(res) // adekang

}

继承

package main

import "fmt"

type Human struct {
	name string
	sex  string
}

func (c *Human) Eat() {
	println("Human Eat")
}

func (c *Human) Walk() {
	println("Human Walk")
}

type SuperMan struct {
	// 继承
	Human
	level int
}

// 重写
func (c *SuperMan) Eat() {
	println("SuperMan Eat")
}
func (c *SuperMan) Fly() {
	println("SuperMan Fly")
}

func (c *SuperMan) Print() {
	fmt.Println(c.name)
	fmt.Println(c.sex)
	fmt.Println(c.level)
}

func main() {
	h := Human{"adekang", "男"}
	h.Eat()
	h.Walk()

	s := SuperMan{Human{"adekang", "男"}, 1}
	s.Eat()  // 子类的方法
	s.Walk() // 父类的方法
	s.Fly()  // 子类的方法
	s.Print()
}

多态

package main

import "fmt"

//  本质是一个指针
type Animal interface {
	Sleep()
	GetColor() string
	GetType() string
}

//  具体的类
type Cat struct {
	color string
}

func (c *Cat) Sleep() {
	fmt.Println("Cat is sleep")
}
func (c *Cat) GetColor() string {
	return c.color
}
func (c *Cat) GetType() string {
	return "Cat"
}

type Dog struct {
	color string
}

func (c *Dog) Sleep() {
	fmt.Println("Dog is sleep")
}
func (c *Dog) GetColor() string {
	return c.color
}
func (c *Dog) GetType() string {
	return "Dog"
}
func main() {
	//  接口的使用
	var animal Animal
	animal = &Cat{"white"}
	animal.Sleep() // 多态的现象,调用的就是Cat的Sleep方法
	fmt.Println(animal.GetColor())
	fmt.Println(animal.GetType())

	animal = &Dog{"black"}
	animal.Sleep() // 多态的现象,调用的就是Dog的Sleep方法
	fmt.Println(animal.GetColor())
	fmt.Println(animal.GetType())

}

输出

Cat is sleep
white
Cat
Dog is sleep
black
Cat

接口

通用万能类型

interface{}

类型断言

package main

import "fmt"

// interface{} 万能类型接口

func myFnc(arg interface{}) {

	//  类型断言
	if v, ok := arg.(int); ok {
		fmt.Println("--my fnc int--", v)
	}

	//  区分类型
	switch arg.(type) {
	case int:
		fmt.Println("my fnc int", arg)
	case string:
		fmt.Println("my fnc string", arg)
	case Book:
		fmt.Println("my fnc Book", arg)
	}
}

type Book struct {
	name string
}

func main() {
	book := Book{"Go语言编程"}
	myFnc(book)
	myFnc(100)
	myFnc("hello")
}

reflect

package main

import (
	"fmt"
	"reflect"
)

func reflectNum(arg interface{}) {
	fmt.Println(reflect.TypeOf(arg))
	fmt.Println(reflect.ValueOf(arg))
}

func main() {

	var num float64 = .2345

	reflectNum(num)
}

获取信息

package main

import (
	"fmt"
	"reflect"
)

type User struct {
	Id   int
	Name string
	Age  int
}

func (c User) Call() {
	println("User Call")
	fmt.Println(c)

}

func main() {

	user := User{1, "adekang", 18}
	DoFiledAndMethod(user)

}

func DoFiledAndMethod(input interface{}) {
	//  获取input的type
	inputType := reflect.TypeOf(input)
	fmt.Println("inputType is ", inputType.Name())

	// 获取input的value
	inputValue := reflect.ValueOf(input)
	fmt.Println("inputValue is ", inputValue)

	//	通过type获取里面的字段
	//	1.获取interface的reflect.Type, 通过Type得到NumField , 进行遍历
	//	2.得到每个field, 数据类型
	//	3.通过filed有一个Interface()方法等到对应的value

	for i := 0; i < inputType.NumField(); i++ {
		filed := inputType.Field(i)
		value := inputValue.Field(i).Interface()
		fmt.Printf("%s: %v = %v\n", filed.Name, filed.Type, value)
	}

	// 通过type获取里面的方法
	// 1.获取interface的reflect.Type, 通过Type得到NumMethod , 进行遍历
	// 2.得到每个method, 数据类型
	// 3.通过method有一个Interface()方法等到对应的func
	for i := 0; i < inputType.NumMethod(); i++ {
		m := inputType.Method(i)
		fmt.Printf("%s: %v\n", m.Name, m.Type)
	}
}

结构体标签

package main

import (
	"fmt"
	"reflect"
)

type resume struct {
	Name string `info:"name" doc:"我的名字"`
	Sex  string `info:"sex"`
}

func findTag(str interface{}) {
	t := reflect.TypeOf(str).Elem()
	for i := 0; i < t.NumField(); i++ {
	tagString	:=t.Field(i).Tag.Get("info")
	fmt.Println("info:",tagString)
	}
}

func main() {
	var re resume
	findTag(&re)

}

输出

info: name
info: sex

结构体标签在json中使用

package main

import (
	"encoding/json"
	"fmt"
)

type Movie struct {
	Title  string   `json:"title"`
	Year   int      `json:"year"`
	Price  int      `json:"price"`
	Actors []string `json:"actors"`
}

func main() {
	movie := Movie{"喜剧之王", 2000, 45, []string{"周星驰", "张柏芝"}}

	//  1. 用json.Marshal()函数将movie结构体序列化为json字符串
	jsonStr, err := json.Marshal(movie)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(jsonStr))

	// 2. 用json.Unmarshal()函数将json字符串反序列化为movie结构体
	// jsonStr := `{"title":"喜剧之王","year":2000,"price":45,"actors":["周星驰","张柏芝"]}`

	my_movie := Movie{}
	err = json.Unmarshal([]byte(jsonStr), &my_movie)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", my_movie)
}

输出

{"title":"喜剧之王","year":2000,"price":45,"actors":["周星驰","张柏芝"]}
{Title:喜剧之王 Year:2000 Price:45 Actors:[周星驰 张柏芝]}