首页 > 其他分享 >Go:一文玩转接口

Go:一文玩转接口

时间:2022-10-24 22:46:23浏览次数:69  
标签:show fmt 接口 玩转 func Go main type

  1. 接口的基本剖析
package main

import "fmt"

type Test interface {
	show()
}

type myString string

func (mys myString) show() {
	fmt.Println(mys)
}

func main() {
	var a myString = "tantianran"
	a.show()
}

输出:

tantianran

定义接口:上述代码中,定义了接口Test,该接口规定了有show()方法,而且,Test接口只有1个方法。

实现接口:接下来就是实现接口,在go中,任意类型只要实现了接口的所有方法(这里的Test接口只有1个方法),那么就实现了该接口(而且是隐式实现),刚提到任意类型,于是这里定义了一个类型为string的自定义类型myString,且由该自定义类型myString实现了show()方法,刚提到只要实现了接口的所有方法就实现了该接口,也就是说自定义的myString类型已经实现了Test接口。

使用接口:定义了类型为myString的变量a,且给它赋值了"tantianran",这时候,它就拥有了show方法。所以说,一个变量不管它是什么类型,只要实现了Test接口,就能调用它的show方法。

  1. 在上一个栗子的基础上,继续看看这个小栗子

刚提到任意类型只要实现了Test接口,就能调用它的show方法,来验证一下

package main

import "fmt"

type Test interface {
	show()
}

type myInts int16

func (myi myInts) show() {
	fmt.Println(myi)
}

func main() {
	var a myInts = 200
	a.show()
}

输出:

200

果然,自定义了一个int16类型的自定义类型myInts,它也用了show方法。

  1. 继续上一个例子,看看下面代码

定义个结构体类型的User试试

package main

import "fmt"

type Test interface {
	show()
}

type User struct {
	name string
	age  int
}

func (u User) show() {
	fmt.Println(u)
}

func main() {
	u := User{"tantianran", 18}
	u.show()
}

输出:

{tantianran 18}
  1. 来一个贴近生活的小栗子
package main

import "fmt"

// 支付接口
type Payment interface {
	Payment() float64
}

// 银行卡
type Bankcard struct {
	CardId     int64
	Moneytotal float64
}

// 结算
func settleAccount(b *Bankcard, p Payment) {
	fmt.Println("正在发生扣款...")
	amount := p.Payment()
	res := b.Moneytotal - amount
	b.Moneytotal = res
}

// 微信
type Weixin struct {
	AccountID string
	Type      string
}

func (w Weixin) Payment() float64 {
	return 65.78
}

// 支付宝
type Zhifubao struct {
	AccountID string
	Type      string
}

func (z Zhifubao) Payment() float64 {
	return 82.12
}

type PingDuoduo struct {
	Commodity string  //商品
	Price     float64 //价格
}

func main() {
	card := Bankcard{CardId: 2349342594759947742, Moneytotal: 1200.89}
	fmt.Println(card.Moneytotal)
	wx := Weixin{AccountID: "ttr", Type: "微信"}
	zfb := Zhifubao{AccountID: "ttr1", Type: "支付宝"}
	settleAccount(&card, wx)
	settleAccount(&card, zfb)

	fmt.Println(card.Moneytotal)

}
  1. 通过接口实现结构体排序

自定义的结构体只要实现了Len、Less、Swap方法,就可以交给标准库中的sort.Sort进行排序。

package main

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

type Hero struct {
	Name string
	Age  int
}

type HeroSlice []Hero

func (hs HeroSlice) Len() int {
	return len(hs)
}

func (hs HeroSlice) Less(i, j int) bool {
	return hs[i].Age < hs[j].Age
}

func (hs HeroSlice) Swap(i, j int) {
	temp := hs[i]
	hs[i] = hs[j]
	hs[j] = temp
}

func main() {
	var heroes HeroSlice
	for i := 0; i < 10; i++ {
		hero := Hero{
			Name: fmt.Sprintf("host-%d", rand.Intn(100)),
			Age:  rand.Intn(100),
		}
		heroes = append(heroes, hero)
	}

	sort.Sort(heroes)
	for _, v := range heroes {
		fmt.Println(v)
	}
}
  1. 函数形参,类型是空接口时可以接收任意类型
package main

import "fmt"

func test(t interface{}) {
	fmt.Println(t)
}

type User struct {
	name string
}

func main() {
	a := 1
	b := "hello"
	c := map[string]int{
		"age": 18,
	}
	u := User{name: "ttr"}

	z := []interface{}{"hello", 100, 89.78, c, a, b}

	test(a)
	test(b)
	test(c)
	test(u)

	test(z)
}
  1. 变量的类型为空接口时,也可以接收任意类型的值
package main

import "fmt"

type myinterface interface{}

func main() {
	var a myinterface = 10
	fmt.Println(a)
	var b myinterface = 89.78
	fmt.Println(b)

	numarr := []int{1, 2, 3, 4, 5}
	var c myinterface = numarr
	fmt.Println(c)

	user := map[string]string{
		"name": "ttr",
		"addr": "gz",
	}
	var d myinterface = user
	fmt.Println(d)
}

本文转载于(喜欢的盆友关注我们):https://mp.weixin.qq.com/s/4MibjHUlqfFtc9gLTXNnmA

标签:show,fmt,接口,玩转,func,Go,main,type
From: https://www.cnblogs.com/ttropsstack/p/16823323.html

相关文章

  • 接口如何体现多态性
     如调用时Computuercom=newComputer();Flashflash=newFlash();com.transform(flash);  publicvoidtransform(USBusb){ //此时相当于USBu......
  • R语言、04 案例P143 Go bananas、《商务与经济统计》案例题
    编程教材《R语言实战·第2版》RobertI.Kabacoff课程教材《商务与经济统计·原书第13版》(安德森)P143、案例GoBananas#1生产中断的概率c<-pbinom(4,......
  • python之第三方库netifaces库:netifaces 模块用于提供有关网络接口及其状态的信息(①获
    前言1、 在系统运维等过程中,网络永远是离不开的话题。网络中比较基础的是网络接口,每个网络接口都有一个名字,并且有它的ip地址,还有关于从这个接口出去的包的路由。我们可......
  • gozero学习之路
    go-zero开始学习go-zero咯https://github.com/Mikaelemmmm/go-zero-looklook环境配置https://github.com/Mikaelemmmm/go-zero-looklook/blob/main/deploy/script/genc......
  • 2 django 创建一个项目
    二、django创建一个项目1.创建项目https://www.cnblogs.com/eosclover/p/16796616.html1.1用专业版创建django项目打开pycharm,点击左上角file-->NewProject......
  • 接口
    packageJiekou;importjavax.management.MBeanAttributeInfo;/***@authorliu$*//*接口的使用1.使用interface来定义2.Java中,类和接口是两种不同的结构3.如何定义接口,......
  • Java 8 函数式接口和Lambda表达式
    Java一直是一种面向对象的编程语言。这意味着Java编程中的一切都围绕着对象(为了简单起见,除了一些基本类型)。我们不仅有Java中的函数,它们还是Class的一部分,我们需......
  • CPI 访问需验证的HTTP接口
    CPI访问外围系统接口时,有时需要先访问验证接口,获取AccessToken或得到账密,然后访问具体接口时,将获取到的验证结果传入具体接口进行访问1、OAuth2.0 AccessToken方式1.1、......
  • IDEA 对项目Maven进行install项目时报错(Failed to execute goal org.apache.maven.plu
    【问题】IDEA对项目Maven进行install项目时报错 错误如下:Failedtoexecutegoalorg.apache.maven.plugins:maven-surefire-plugin:3.0.0-M5:test(default-test)o......
  • Python - Locust对接口进行压测
    我们在做性能测试主要去看的就是以上四点:错误率,响应时间,tps和rps当我们使用Python去构建自动化测试框架时,我们用Locust来对接口进行压测,具体写法如下:首先我们需要在cmd中......