接口
接口的使用
定义接口
package main
import "fmt"
type DefinedInterface interface {
HelloWorld()
}
type DefinedStruct struct {
name string
gender string
}
func (STR DefinedStruct) HelloWorld() {
fmt.Println("定义接口, 定义结构体, 实现结构方法")
fmt.Println("Hello World")
}
func main() {
var S DefinedInterface
S = new(DefinedStruct)
S.HelloWorld()
}
interface 值
package main
import (
"fmt"
)
type Person struct {
name string
}
type Student struct {
Person
salary float64
}
type Programmer struct {
Person
salary float64
}
func (p Person) SayHi() {
fmt.Printf("我的名字叫:%s", p.name)
}
func (p Person) Sing(lyrics string) {
fmt.Println(lyrics)
}
func (p Programmer) SayHi() {
fmt.Printf("我的名字叫:%s,我的工资:%f", p.name, p.salary)
}
func main() {
p := Person{"Joker Even"}
p.SayHi()
Pro := Programmer{Person{"Joker Even"}, 3000000}
Pro.SayHi()
}
嵌入 interface
package main
import "fmt"
type Interface interface{
Hi()
}
type INTERFACE interface{
Interface
}
type Test struct{
}
func (t *Test) Hi(){
fmt.Println("OK")
}
func main(){
var I INTERFACE
I = new(Test)
I.Hi()
}
接口的类型和断言
package main
import "fmt"
func main() {
var i1 interface{} = new(Student)
s := i1.(Student)
fmt.Println(s)
var i2 interface{} = new(Student)
s, ok := i2.(Student)
if ok {
fmt.Println(s)
}
}
type Student struct {
}
另一种形式
switch ins:=s.(type) {
case Triangle:
fmt.Println("三角形。。。",ins.a,ins.b,ins.c)
case Circle:
fmt.Println("圆形。。。。",ins.radius)
case int:
fmt.Println("整型数据。。")
}
type 关键字
package main
import (
"fmt"
"strconv"
)
func main() {
res1 := fun1()
fmt.Println(res1(10,20))
}
type my_fun func (int,int)(string)
func fun1 () my_fun{
fun := func(a,b int) string {
s := strconv.Itoa(a) + strconv.Itoa(b)
return s
}
return fun
}