Golang | Golang 基础

Go interfaces and assertions

package main

import "fmt"

func main() {
    
    
	var b = &Bird{
    
    
		"斑鸠",
		"蚂蚱",
		"鸟类",
	}
	Display(b)
}

// 定义一个通用接口:动物接口
type Animal interface {
    
    
	Breath() // 动物都具备 呼吸方法
}

// 定义一个鸟类:其呼吸的方式是在陆地
type Bird struct {
    
    
	Name string
	Food string
	Kind string
}

func (b *Bird) Breath() {
    
    
	fmt.Println("鸟 在 陆地 呼吸")
}

// 一个普通函数,参数是动物接口
func Display(a Animal) {
    
    
	// 直接调用接口中的方法
	a.Breath()
}

The interface type cannot directly access the members of its specific implementation class. It is necessary to use type assertions to judge the type of the interface. The type assertion format:

t := i.(T)			//不安全写法:如果i没有完全实现T接口的方法,这个语句将会触发宕机
t, ok := i.(T)		// 安全写法:如果接口未实现接口,将会把ok掷为false,t掷为T类型的0值
  • i stands for interface variable
  • T represents the target type of conversion
  • t represents the transformed variable

The Dsiplay of the above case can be written as:

func Display(a Animal) {
    
    
	// 直接调用接口中的方法
	a.Breath()
	// 调用实现类的成员:此时会报错
	instance, ok := a.(*Bird)	// 注意:这里必须是 *Bird类型,因为是*Bird实现了接口,不是Bird实现了接口
	if ok {
    
    
		// 得到了具体的实现类,才能访问实现类的成员
		fmt.Println("该鸟类的名字是:", instance.Name)
	} else {
    
    
		fmt.Println("该动物不是鸟类")
	}
}

Go implementation

package main

import (
	"fmt"
)

func main() {
    
    
	// 实现九九乘法表
	for i := 1; i < 10; i++ {
    
    
		for j := 1; j <= i; j++ {
    
    
			fmt.Printf("%d * %d = %d ", i, j, i*j)
		}
		fmt.Println()
	}
	fmt.Println("==================================================================================================================")
	// 实现1~n阶乘之和
	fmt.Println("1~n阶乘之和为", sum(10))
	fmt.Println("==================================================================================================================")
	// 实现n个斐波那契数列
	fmt.Println("n个斐波那契数列", fibonacci(10))
}
func sum(n int) (sum int) {
    
    
	sum = 0
	for i := n; i > 0; i-- {
    
    
		sum += factorial(i)
	}
	return
}
func factorial(n int) int {
    
    
	if n == 1 {
    
    
		return 1
	}
	return n * factorial(n-1)
}

func fibonacci(n int) []int {
    
    
	var s []int
	a, b := 0, 1
	for i := 1; i < n+1; i++ {
    
    
		a, b = b, a+b
		s = append(s, a)
	}
	return s
}

Guess you like

Origin blog.csdn.net/y1534414425/article/details/105753207