golang中接口對象的轉(zhuǎn)型兩種方式
接口對象的轉(zhuǎn)型有兩種方式:
1. 方式一:instance,ok:=接口對象.(實際類型)
如果該接口對象是對應的實際類型,那么instance就是轉(zhuǎn)型之后對象,ok的值為true
配合if...else if...使用
2. 方式二:
接口對象.(type)
配合switch...case語句使用
示例:
package main
import (
"fmt"
"math"
)
type shape interface {
perimeter() int
area() int
}
type rectangle struct {
a int // 長
b int // 寬
}
func (r rectangle) perimeter() int {
return (r.a + r.b) * 2
}
func (r rectangle) area() int {
return r.a * r.b
}
type circle struct {
radios int
}
func (c circle) perimeter() int {
return 2 * c.radios * int(math.Round(math.Pi))
}
func (c circle) area() int {
return int(math.Round(math.Pow(float64(c.radios), 2) * math.Pi))
}
func getType(s shape) {
if i, ok := s.(rectangle); ok {
fmt.Printf("長方形的長:%d,長方形的寬是:%d\n", i.a, i.b)
} else if i, ok := s.(circle); ok {
fmt.Printf("圓形的半徑是:%d\n", i.radios)
}
}
func getType2(s shape) {
switch i := s.(type) {
case rectangle:
fmt.Printf("長方形的長:%d,長方形的寬是:%d\n", i.a, i.b)
case circle:
fmt.Printf("圓形的半徑是:%d\n", i.radios)
}
}
func getResult(s shape) {
fmt.Printf("圖形的周長是:%d,圖形的面積是:%d\n", s.perimeter(), s.area())
}
func main() {
r := rectangle{a: 10, b: 20}
getType(r)
getResult(r)
c := circle{radios: 5}
getType2(c)
getResult(c)
}
上面的例子使用的是方式一,如果要使用方式2,可以將getType()函數(shù)改為:
func getType(s shape) {
switch i := s.(type) {
case rectangle:
fmt.Printf("圖形的長:%.2f,圖形的寬:%.2f \n", i.a, i.b)
case triangle:
fmt.Printf("圖形的第一個邊:%.2f,圖形的第二個邊:%.2f,圖形的第三個邊:%.2f \n",i.a,i.b,i.c)
case circular:
fmt.Printf("圖形的半徑:%.2f \n",i.radius)
}
}
PS:上面求三角形面積使用了海倫公式求三角形的面積,公式為:
三角形的面積=平方根[三角形周長的一半×(三角形周長的一半減去第一個邊)×(三角形周長的一半減去第二個邊)×(三角形周長的一半減去第三個邊)]
到此這篇關(guān)于golang中接口對象的轉(zhuǎn)型的文章就介紹到這了,更多相關(guān)golang接口對象內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

