美国纽约大学研究生学费与生活费总预算是多少?

知识 1℃

接口对象的中接转型转型有两种编制  :

1. 编制一 :instance,ok:=接口对象.(理论圭表类型)

  假定该接口对象是对应的理论圭表类型 ,那么instance就是口对转型此后对象 ,ok的两种值为true
  合营if...else if...独霸

2. 编制二 :

  接口对象.(type)
  合营switch...case语句独霸

示例 :

package main import (    "fmt"    "math") type shape inte***ce {     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 ***:  fmt.Printf("图形的第一个边	:%.2f,图形的两种第二个边:%.2f,图形的编制第三个边
:%.2f \n",i.a,i.b,i.c) case circular:  fmt.Printf("图形的半径:%.2f \n",i.radius) }}

PS:上面求三角形面积独霸了海***式求三角形的面积  ,公式为:

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

到此这篇关于golang中接口对象的转型的文章就引见到这了,更多相干Golang接口对象内容请搜刮完竣下载之前的文章或延续不雅不雅不雅不雅鉴赏上面的相干文章希看大年夜师往后多多支撑完竣下载!

口对