【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 {
/* variables */
}
/* 實作介面方法 */
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()
}
輸出結果:
好好學習, 天天向上
一天天的, 就知道打游戲
燒殺搶掠, 無惡不作

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/294057.html
標籤:其他
