栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

【Golang】✔️走进 Go 语言✔️ 第十五课 递归 & 接口

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Golang】✔️走进 Go 语言✔️ 第十五课 递归 & 接口

【Golang】✔️走进 Go 语言✔️ 第十五课 递归 & 接口
  • 概述
  • 递归
    • 实现阶乘
    • 斐波那契数列
  • 接口

概述

Golang 是一个跨平台的新生编程语言. 今天小白就带大家一起携手走进 Golang 的世界. (第 15 课)

递归

递归 (Recursion) 就是在运行的过程中自己调用自己.

实现阶乘
package main

import "fmt"

func main() {

	// 递归实现阶乘
	result := factorial(5)

	//调试输出
	fmt.Println(result)

}

func factorial(n int) int {
	
	//递归
	if (n > 1) {
		return n * factorial(n - 1)
	} else {
		return 1
	}

}

输出结果:

120
斐波那契数列
package main

import "fmt"

func main() {

	// 递归实现斐波那契
	result := fiboacci(10)
	
	// 调试输出
	fmt.Print(result)

}

func fiboacci(num int) int {

	if num < 3 {
		return num
	} else {
		return fiboacci(num-1) + fiboacci(num-2)
	}
}

输出结果:

89
接口

接口 (Interface) 可以帮助我们把所有具有共性的方法定义在一起. Go 的接口类型是对其他类型行为的抽象和概括. 因为接口和类型不会和特定的实现细节绑定在一起, 通过这种抽象的方式我们可以让对象更加零花和具有适应能力. 任何其他类型只要实现了这些方法就是实现了这个接口. (和多态类似)

格式:

type interface_name interface {
   method_name1 [return_type]
   method_name2 [return_type]
   method_name3 [return_type]
   ...
   method_namen [return_type]
}


type struct_name struct {
   
}


func (struct_name_variable struct_name) method_name1() [return_type] {
   
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
   
}

例子:

package main

import "fmt"

// 定义接口
type student interface{
	study()
}

// 定义结构体
type good_student struct {}

type bad_student struct {}

type horrible_student struct {}

// 定义方法
func (stu good_student) study() {
	fmt.Println("好好学习, 天天向上")
}

func (stu bad_student) study() {
	fmt.Println("一天天的, 就知道打游戏")
}

func (stu horrible_student) study() {
	fmt.Println("烧杀抢掠, 无恶不作")
}

// 主函数
func main() {

	var stud1 student = new(good_student)
	stud1.study()

	var stud2 student = new(bad_student)
	stud2.study()

	var stud3 student = new(horrible_student)
	stud3.study()

}

输出结果:

好好学习, 天天向上
一天天的, 就知道打游戏
烧杀抢掠, 无恶不作

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/909254.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号