【GO语言高级编程学习】之语言基础——函数、方法和接口

徐晔
2023-12-01

函数

函数是一段专门用于完成特定工作的代码。在 Go 语言中,函数主要有具名和匿名之分。具名函数正常定义使用即可。匿名函数可以赋值给变量,然后由变量调用;也可以在定义时调用。

package main

import "fmt"

// MyPrint 打印字符串
func MyPrint(str string) {
	fmt.Println(str)
}

func main() {
	MyPrint("hello golang")

	// 将匿名函数赋值给变量
	var a = func(str string) {
		fmt.Println(str)
	}
	a("hello golang")

	// 在定义时调用匿名函数
	func(str string) {
		fmt.Println(str)
	}("hello golang")
}

可变数量参数

// findMinNum 找到最小值
func findMinNum(a int, more ...int) int {
	minNum := a
	for _, v := range more {
		if minNum > v {
			minNum = v
		}
	}
	return minNum
}

fmt.Println(findMinNum(8, 7, 6, 5, 4, 3, 2, 1)) // 1

方法

方法一般是面向对象编程(OOP)的一个特性,定义在类中的函数,它用于操作类的实例(即对象)的数据。Go语言中的方法是与类型绑定的,下面以学生类为例,写出每个属性的set方法。

type Student struct {
	name  string
	id    int64
	score int64
}

func (s *Student) SetName(name string) {
	s.name = name
}

func (s *Student) SetID(id int64) {
	s.id = id
}

func (s *Student) SetScore(score int64) {
	s.score = score
}

继承
Go语言的继承不像其他面向对象语言那么复杂,没有public,private等区别,只是实现了类似继承的区别。

type People struct {
	name   string
	height float64
	weight float64
}

type Student struct {
	id    int64
	score int64
	People
}

func (p *People) SetName(name string) {
	p.name = name
}

func (s *Student) SetScore(score int64) {
	s.score = score
}

func Main1_2() {
	var a Student
	a.People.SetName("zhang san") // 等价于 a.SetName("zhang san")
	a.SetScore(100)
	fmt.Println(a.name, a.score) // zhang san 100
}

接口

Go语言提供了一种数据类型,即接口。它把所有具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。接口可以让我们将不同的类型绑定到一组公共的方法上,从而实现多态和灵活的设计。Go 语言中接口类型的独特之处在于它是满足隐式实现的鸭子类型:这个概念的名字来源于由詹姆斯·惠特科姆·莱利提出的鸭子测试,“鸭子测试”可以这样表述:“如果它走起来像鸭子,游泳起来像鸭子,叫起来也像鸭子,那么它就是一只鸭子”。下面的代码是kratos框架中的一个接口代码的示例。

// auth.go
type AuthRepo interface {
	CreateAuth(ctx context.Context, auther *Auth) (string, error)
	UpdataAuth(ctx context.Context, auther *Auth) (string, error)
	GetAuthInfo(ctx context.Context, auther *Auth) (string, error)
	FindAuthByID(ctx context.Context, id string) (string, error)
}
// data.go
func (r *AuthRepo) CreateAuth(ctx context.Context, auther *biz.Auth) (string, error) {
	return "",nil
}
func (r *AuthRepo) UpdataAuth(ctx context.Context, auther *biz.Auth) (string, error) {
	return "",nil
}
func (r *AuthRepo) GetAuthInfo(ctx context.Context, auther *biz.Auth) (string, error) {
	return "",nil
}
func (r *AuthRepo) FindAuthByID(ctx context.Context, id string) (string, error) {
	return "",nil
}
 类似资料: