golang基础-接口、接口嵌套、类型断言、接口与结构体_接口等转换

前端之家收集整理的这篇文章主要介绍了golang基础-接口、接口嵌套、类型断言、接口与结构体_接口等转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

接口

package main

import "fmt"
type Test interface {
    Print()
    Sleep()
}

type Student struct {
    name  string
    age   int
    score int
}
/*student实现接口Print方法*/
func (p Student) Print() {
    fmt.Println("name:",p.name)
    fmt.Println("age:",p.age)
    fmt.Println("score:",p.score)
}
/*student实现接口Sleep方法*/
func (p Student) Sleep() {
    fmt.Println("student sleep")
}


func main() {

    var t Test
    fmt.Println(t)
    fmt.Println("--------------------")

    var stu Student = Student{
        name:  "stu1",age:   20,score: 200,}
    //使用接口方法
    t = stu
    t.Print()
    t.Sleep()

    fmt.Println("=============")
    fmt.Println("t:",t)
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
<nil>
--------------------
name: stu1
age: 20
score: 200
student sleep
=============
t: {stu1 20 200}
PS E:\golang\go_pro\src\safly>

或者如下的代码也可以:

package main

import "fmt"
type Test interface {
    Print()
    Sleep()
}

type Student struct {
    name  string
    age   int
    score int
}
/*student实现接口Print方法*/
func (p *Student) Print() {
    fmt.Println("name:",(*p).name)
    fmt.Println("age:",(*p).age)
    fmt.Println("score:",(*p).score)
}
/*student实现接口Sleep方法*/
func (p *Student) Sleep() {
    fmt.Println("student sleep")
}


func main() {

    var t Test
    fmt.Println(t)
    fmt.Println("--------------------")

    var stu *Student = &Student{
        name:  "stu1",t)
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
<nil>
--------------------
name: stu1
age: 20
score: 200
student sleep
=============
t: &{stu1 20 200}
PS E:\golang\go_pro\src\safly>

sort接口实现

一种事物的多种形态,都可以按照统一的接口进行操作
我们来做一个例子,通过实现sort接口,来对切片实现排序

package main

import (
    "fmt"
    "math/rand"
    "sort"
)

type Student struct {
    Name     string
    Id       string
    Age      int
    sortType int
}

type Book struct {
    Name   string
    Author string
}
//别名
type StudentArray []Student

func (p StudentArray) Len() int {
    return len(p)
}

func (p StudentArray) Less(i,j int) bool {
    return p[i].Name < p[j].Name
}

func (p StudentArray) Swap(i,j int) {
    p[i],p[j] = p[j],p[i]
}

func main() {
    var stus StudentArray
    for i := 0; i < 10; i++ {
        stu := Student{
            Name: fmt.Sprintf("stu%d",rand.Intn(100)),Id:   fmt.Sprintf("110%d",rand.Int()),Age:  rand.Intn(100),}

        stus = append(stus,stu)
    }

    for _,v := range stus {
        fmt.Println(v)
    }

    fmt.Println("\n\n")
    sort.Sort(stus)
    for _,v := range stus {
        fmt.Println(v)
    }
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
{stu81 1108674665223082153551 47 0}
{stu59 1103916589616287113937 18 0}
{stu25 1101443635317331776148 56 0}
{stu0 1104751997750760398084 11 0}
{stu62 1103510942875414458836 28 0}
{stu74 1102610529275472644968 45 0}
{stu37 1102015796113853353331 95 0}
{stu66 1105263531936693774911 58 0}
{stu47 1102740103009342231109 87 0}
{stu88 1107981306761429961588 15 0}



{stu0 1104751997750760398084 11 0}
{stu25 1101443635317331776148 56 0}
{stu37 1102015796113853353331 95 0}
{stu47 1102740103009342231109 87 0}
{stu59 1103916589616287113937 18 0}
{stu62 1103510942875414458836 28 0}
{stu66 1105263531936693774911 58 0}
{stu74 1102610529275472644968 45 0}
{stu81 1108674665223082153551 47 0}
{stu88 1107981306761429961588 15 0}
PS E:\golang\go_pro\src\safly>

接口嵌套

package main

import "fmt"

type Reader interface {
    Read()
}

type Writer interface {
    Write()
}

type ReadWriter interface {
    Reader
    Writer
}

type File struct {
}

func (f *File) Read() {
    fmt.Println("read data")
}

func (f *File) Write() {
    fmt.Println("write data")
}
//类似java里面的多态
func TestReader(r Reader) {
    r.Read()
}

//测试接口嵌套
func Test(rw ReadWriter) {
    rw.Read()
    rw.Write()
}


func main() {
    var f File
    //多态
    TestReader(&f)
    //嵌套接
    Test(&f)

}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
read data
read data
write data
PS E:\golang\go_pro\src\safly>

类型断言

类型断言,由于接口是一般类型,不知道具体类型,如果要转成具体类型

接口.()转换方式
package main

import "fmt"


func main() {
    var i int
    var inter interface{}

    inter = i
    a:=inter.(int)
    fmt.Printf("%d,%T\n",a,a)
    fmt.Printf("%d,inter,inter)
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
0,int
0,int
PS E:\golang\go_pro\src\safly>

或者如下更简单方式

package main

import "fmt"

func Test(a interface{}){
    fmt.Printf("%d,a)

}

func main() {
    var b int 
    Test(b)
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
0,int
PS E:\golang\go_pro\src\safly>
结构体转为接口
package main

import "fmt"

type Stu struct{
    Name string
    Sex string
}

func Test(a interface{}){
    b,ok := a.(Stu)
    if ok == false{
        fmt.Println("convert Failed")
        return
    }
    b.Name = "safly"
    fmt.Println(b)

}

func main() {
    var b Stu 
    Test(b)
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
{safly }
PS E:\golang\go_pro\src\safly>
结构体指针转为接口
package main

import "fmt"

type Student struct {
    Name string
    Sex  string
}

func Test(a interface{}) {
    b,ok := a.(*Student)
    if ok == false {
        fmt.Println("convert Failed")
        return
    }
    fmt.Println(*b)
}


func main() {
    var b Student = Student{
        Name: "stu01",Sex:  "female",}
    Test(&b)
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
{stu01 female}
PS E:\golang\go_pro\src\safly>
接口转为接口
package main

import "fmt"

type Reader interface {
    Read()
}

type Writer interface {
    Write()
}

type ReadWriter interface {
    Reader
    Writer
}

type File struct {
}

func (f *File) Read() {
    fmt.Println("read data")
}

func (f *File) Write() {
    fmt.Println("write data")
}

func Test(rw ReadWriter) {
    rw.Read()
    rw.Write()
}

func main() {
    var f *File
    var b interface{}
    b = f

    //结构体指针
    c:=b.(*File)
    c.Read()
    //接口赋值接口
    oo := b.(Reader)
    oo.Read()
    //接口赋值接口
    v := b.(ReadWriter)
    v.Read()
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
read data
read data
read data
PS E:\golang\go_pro\src\safly>
switch x.(type) 转换方式
package main

import "fmt"

type Student struct {
    Name string
    Sex  string
}


func just(items ...interface{}) {
    for index,v := range items {
        switch v.(type) {
        case bool:
            fmt.Printf("%d params is bool,value is %v\n",index,v)
        case int,int64,int32:
            fmt.Printf("%d params is int,v)
        case float32,float64:
            fmt.Printf("%d params is float,v)
        case string:
            fmt.Printf("%d params is string,v)
        case Student:
            fmt.Printf("%d params student,v)
        case *Student:
            fmt.Printf("%d params *student,v)
        }
    }
}

func main() {
    var b Student = Student{
        Name: "stu01",}

    just(28, 8.2,"this is a test",b,&b)
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
0 params is int,value is 28
1 params is float,value is 8.2
2 params is string,value is this is a test
3 params student,value is {stu01 female}
4 params *student,value is &{stu01 female}
PS E:\golang\go_pro\src\safly>
原文链接:https://www.f2er.com/go/187755.html

猜你在找的Go相关文章