华域联盟 Golang golang中接口对象的转型两种方式

golang中接口对象的转型两种方式

接口对象的转型有两种方式:

1. 方式一:instance,ok:=接口对象.(实际类型)

  如果该接口对象是对应的实际类型,那么instance就是转型之后对象,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()函数改为:

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:上面求三角形面积使用了海伦公式求三角形的面积,公式为:

三角形的面积=平方根[三角形周长的一半×(三角形周长的一半减去第一个边)×(三角形周长的一半减去第二个边)×(三角形周长的一半减去第三个边)]

到此这篇关于golang中接口对象的转型的文章就介绍到这了,更多相关golang接口对象内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

本文由 华域联盟 原创撰写:华域联盟 » golang中接口对象的转型两种方式

转载请保留出处和原文链接:https://www.cnhackhy.com/111519.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

关于Go 空结构体的 3 种使用场景

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们