Go函数,方法,接口

函数

package main

import "fmt"

// 具名函数
func Add(a, b int) int {
	return a + b
}

// 匿名函数
var Add2 = func(a, b int) int {
	return a + b
}

//多输入参数,多返回值
var Add3 = func(a int, more ...int) (int, int) {
var sum = 0;
for _, v := range more {
	sum += v;
}

return a, sum;
}

func main() {

fmt.Println(Add(1, 3))

fmt.Println(Add2(1, 3))

a, b := Add3(1, 2, 3, 4)
fmt.Println(a, b)

//闭包函数
for i := 0; i < 3; i++ {
	defer func() { println(i) }()
}

for i := 0; i < 2; i++ {
	j := i
	defer func() { println(j) }()
}
}

方法

package main

import "fmt"

type personmgs struct {
	name string
	age  int
	like []int
}

func (person personmgs) DisplayPerson() {
	fmt.Println(person.age, person.name, person.like)
}

func (person *personmgs) AddAge(number int) {
	person.age += number
}

type woman struct {
	personmgs
	sex string
}

func main() {
	var wp personmgs
	wp.name = "www"
	wp.age = 99
	wp.like = append(wp.like, []int{1, 2, 3}...)

	fmt.Println(wp);
	wp.DisplayPerson()

	wp.AddAge(1)
	wp.DisplayPerson()

	var nv woman
	nv.age = 77
	nv.sex = "女"
	fmt.Println(nv)
}

接口

package main

import (
	"fmt"
)

type Area interface {
	GetArea() float32
}

type Rect struct {
	x float32
	y float32
	w float32
	h float32
}

func (rect Rect) GetArea() float32 {
	return rect.h * rect.w
}

type Cricle struct {
	x float32
	y float32
	w float32
}

func (cricle Cricle) GetArea() float32 {
	return cricle.w * cricle.w * 3.14
}

/// 类似纯虚函数
type LING struct {
	Area
	x float32
	y float32
}

func (lin LING) GetArea() float32 {
	return lin.x * lin.y
}

//具有0个方法的接口称为空接口。它表示为interface {}。由于空接口有0个方法,所有类型都实现了空接口
func findType(i interface{}) {
	switch i.(type) {
	case string:
		fmt.Printf("String: %s\n", i.(string))
	case int:
		fmt.Printf("Int: %d\n", i.(int))
	default:
		fmt.Printf("Unknown type\n")
	}
}

func main() {

	var rect = Rect{1, 2, 3, 4}
	fmt.Println(rect)

	var cricle = Cricle{1, 2, 3}
	fmt.Println(cricle)

	var area Area = rect
	fmt.Printf("%v \n", area.GetArea())
	fmt.Printf("Type = %T, value = %v\n", area, area) //Type = main.Rect, value = {1 2 3 4}

	area = cricle
	fmt.Printf("%v \n", area.GetArea())
	fmt.Printf("Type = %T, value = %v\n", area, area) //Type = main.Cricle, value = {1 2 3}

	var lin LING
	lin.x = 1
	lin.y = 9
	area = lin
	fmt.Println(lin.GetArea(), area.GetArea())
	fmt.Printf("Type = %T, value = %v\n", area, area) //Type = main.LING, value = {<nil> 1 9}

	findType("www")
	findType(666)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值