介面或結構體的巢狀(struct,interface)
阿新 • • 發佈:2018-12-17
1、結構體的巢狀一
package main
import "fmt"
type Person struct {
name string
}
type Student struct {
class int
person Person //定義person 型別為Person
}
func main(){
s := Student{1,Person{"xiaoming"}}
fmt.Println("name :",s.person.name) //訪問嵌入結構體的變數
}
//執行結果:
//name : xiaoming
2、結構體的巢狀二
package main import "fmt" type Person struct { name string } type Student struct { class int Person //我們直接將Person引入到Student } func main(){ s := Student{1,Person{"xiaoming"}} fmt.Println("name :",s.name) //訪問時可以直接訪問s.name 而不需要s.person.name } //執行結果: //name: xiaoming
3、介面巢狀(定義)
定義介面,在go語言中,介面是定義了型別一系列方法的列表,如果一個型別實現了該介面所有的方法,那麼該型別就符合該介面
package main import "fmt" import "math" type Shape interface { area() float64 } type Rectangle struct { width float64 height float64 } type Circle struct { radius float64 } func (r Rectangle) area() float64 { return r.height * r.width } func (c Circle) area() float64 { return math.Pi * math.Pow(c.radius,2) } func getArea(shape Shape) float64 { return shape.area() } func main(){ r := Rectangle{20,10} c := Circle{4} fmt.Println("Rectangle Area =",getArea(r)) fmt.Println("Circle Area =",getArea(c)) } //執行結果: //Rectangle Area = 200 //Circle Area = 50.26548245743669
4、介面巢狀
package main import "fmt" import "math" type Shape interface { area() float64 } type MultiShape interface { Shape //嵌入式 } type Rectangle struct { width float64 height float64 } type Circle struct { radius float64 } func (r Rectangle) area() float64 { return r.height * r.width } func (c Circle) area() float64 { return math.Pi * math.Pow(c.radius,2) } func getArea(shape MultiShape) float64 { //改為MultiShape return shape.area() } func main(){ r := Rectangle{20,10} c := Circle{4} fmt.Println("Rectangle Area =",getArea(r)) fmt.Println("Circle Area =",getArea(c)) } //執行結果: //Rectangle Area = 200 //Circle Area = 50.26548245743669 //執行結果一致