1. 程式人生 > >Go語言基礎(十)—— Go語言介面

Go語言基礎(十)—— Go語言介面

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 SalaryCalculator interface {
	CalculateSalary() int
}
// 普通挖掘機員工
type Contract struct {
	empId  int
	basicpay int
}
// 有藍翔技校證的員工
type Permanent struct {
	empId  int
	basicpay int
	jj int // 獎金
}

func (p Permanent) CalculateSalary() int {
	return p.basicpay + p.jj
}

func (c Contract) CalculateSalary() int {
	return c.basicpay
}
// 總開支
func totalExpense(s []SalaryCalculator) {
	expense := 0
	for _, v := range s {
		expense = expense + v.CalculateSalary()
	}
	fmt.Printf("總開支 $%d", expense)
}

func main() {
	pemp1 := Permanent{1,3000,10000}
	pemp2 := Permanent{2, 3000, 20000}
	cemp1 := Contract{3, 3000}
	employees := []SalaryCalculator{pemp1, pemp2, cemp1}
	totalExpense(employees)
}

型別斷言

型別斷言用於提取介面的基礎值,語法:i.(T)

package main

import(
"fmt"
)

func assert(i interface{}){
    s:= i.(int)
    fmt.Println(s)
}

func main(){
  var s interface{} = 55
  assert(s)
}

型別判斷

package main

import (  
    "fmt"
)

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() {  
    findType("Naveen")
    findType(77)
    findType(89.98)
}