Go语言之Interface(一)
Go语言之Interface(一)
什么是interface
在面向对象语言中接口是:接口定义了一个对象的行为,但在Go中接口就是方法签名的集合,当一个类型提供了这个接口中的所有的方法,就可以说这个类型实现了这个接口
接口的声明和实现
package main
import (
"fmt"
)
// 接口的声明
type VowelsFinder interface {
FindVowels() []rune
}
type MyString string
// 接口的实现
func (ms MyString) FindVowels() []rune {
var vowels []rune
for _, rune := range ms {
if rune == 'a' || rune == 'e' || rune == 'i' || rune == 'o' || rune == 'u' {
vowels = append(vowels, rune)
}
}
return vowels
}
func main() {
name := MyString("Sam Andreson")
var v VowelsFinder
v = name
fmt.Printf("Vowels are %c", v.FindVowels())
}
声明一个接口
// 接口的声明
type VowelsFinder interface {
FindVowels() []rune
}
实现接口
type MyString string
// 接口的实现
func (ms MyString) FindVowels() []rune {
var vowels []rune
for _, rune := range ms {
if rune == 'a' || rune == 'e' || rune == 'i' || rune == 'o' || rune == 'u' {
vowels = append(vowels, rune)
}
}
return vowels
}
练习使用接口
type SalaryCalculator interface {
CalculateSalary() int
}
type Permanent struct {
empId int
basicpay int
pf int
}
type Contract struct {
empId int
basicpay int
}
func (p Permanent) CalculateSalary() int {
return p.basicpay + p.pf
}
func (c Contract) CalculateSalary() int {
return c.basicpay
}
func totalExpense(s []SalaryCalculator) {
expense := 0
for _, v := range s {
expense = expense + v.CalculateSalary()
}
fmt.Printf("Totla Expense per Month $%d", expense)
}
func main() {
pemp1 := Permanent{1, 5000, 20}
pemp2 := Permanent{2, 5000, 30}
cemp1 := Contract{3, 3000}
employes := []SalaryCalculator{pemp1, pemp2, cemp1}
totalExpense(employes)
}
接口的内部表示
接口内部可以看着是一个元组 (type,value),type表示接口的具体类型,value表示这个具体类型的值
type Test interface {
Tester()
}
type MyFloat float64
func (m MyFloat) Tester() {
fmt.Println(m)
}
func describe(t Test) {
fmt.Printf("Interface type %T value %v\n", t, t)
}
func main() {
var t Test
f := MyFloat(89.4)
t = f
describe(t)
t.Tester()
}
输出结果
Interface type main.MyFloat value 89.4
89.4
空接口
如果一个接口没有包含方法,那么这个接口就是一个空接口 interface{},由于空接口中没有方法,所以所有的类型都可以实现空接口
func descrip(i interface{}) {
fmt.Printf("Type = %T,value = %v\n", i, i)
}
func main() {
s := "Hello,World"
descrip(s)
i := 55
descrip(i)
strt := struct {
name string
}{
name: "CoderMiner",
}
descrip(strt)
}
输出结果是
Type = string,value = Hello,World
Type = int,value = 55
Type = struct { name string },value = {CoderMiner}
类型断言(类型转换)
类型转换的语法 i.(T),把i转换为类型T
如转换为int类型
func asstert(i interface{}) {
s := i.(int)
fmt.Println(s)
}
var s1 interface{} = 56
asstert(s1)
但如果在类型转换时,如果是不同类型转换会发生什么呢?
如string转换为int时
func asstert(i interface{}) {
s := i.(int)
fmt.Println(s)
}
var s1 interface{} = "hello"
asstert(s1)
输出结果是
panic: interface conversion: interface {} is string, not int
会触发panic,类型转换失败,如果要避免出现panic,可以使用下面的方法
v, ok := i.(T)
如果能够转换成功,ok的值是true,转换失败就是false
func asstert(i interface{}) {
s, ok := i.(int)
fmt.Println(s, ok)
}
var s1 interface{} = "hello"
asstert(s1)
var s2 interface{} = 56
asstert(s2)
输出结果
0 false
56 true
类型判断
语法是
i.(type)
func FindType(i interface{}) {
switch i.(type) {
case string:
fmt.Printf("this is the string type and the value is %s\n", i.(string))
case int:
fmt.Printf("this is the int type and the value is %d\n", i.(int))
default:
fmt.Printf("Unknown type\n")
}
}
FindType("CoderMiner")
FindType(77)
FindType(69.3)
Go语言之Interface(一)的更多相关文章
- 浅析Go语言的Interface机制
前几日一朋友在学GO,问了我一些interface机制的问题.试着解释发现自己也不是太清楚,所以今天下午特意查了资料和阅读GO的源码(基于go1.4),整理出了此文.如果有错误的地方还望指正. GO语 ...
- Go语言之Interface(二)
使用指针接收器和值接收器实现接口 type Describer interface { Describe() } type Person struct { name string age int } ...
- Go语言入门——interface
1.Go如何定义interface Go通过type声明一个接口,形如 type geometry interface { area() float64 perim() float64 } 和声明一个 ...
- 浅解 go 语言的 interface(许的博客)
我写了一个 go interface 相关的代码转换为 C 代码的样例.也许有助于大家理解 go 的 interface.不过请注意一点,这里没有完整解析 go 语言 interface 的所有细节. ...
- Go语言第一深坑:interface 与 nil 的比较
interface简介 Go 语言以简单易上手而著称,它的语法非常简单,熟悉 C++,Java 的开发者只需要很短的时间就可以掌握 Go 语言的基本用法. interface 是 Go 语言里所提供的 ...
- Go语言的接口interface、struct和组合、继承
Go语言的interface概念相对于C++中的基类,通过interface来实现多态功能. 在C++中,当需要实现多态功能时,步骤是首先定义一个基类,该基类使用虚函数或者纯虚函数抽象了所有子类会用到 ...
- go 语言 interface{} 的易错点
一,interface 介绍 如果说 goroutine 和 channel 是 go 语言并发的两大基石,那 interface 就是 go 语言类型抽象的关键.在实际项目中,几乎所有的数据结构最底 ...
- 脚本语言:Xmas(二)
本篇,来谈谈类型系统,以及部分与垃圾收集器相关的内容. 一.基本类型 Xmas的基本类型:Null.Boolean.Label.String.Ref.Function.Integer.Float.De ...
- Go语言之三驾马车
作者:唐郑望,腾讯后台开发 工程师商业转载请联系腾讯WeTest获得授权,非商业转载请注明出处. WeTest 导读 Go语言的三个核心设计: interface | goroutine | cha ...
随机推荐
- EOS 权限
[EOS权限] 1.查看权限 cleos get account $(Account_Name) 2.使用 cleos set account permission 命令来修改权限 可以看到,owne ...
- “AS3.0高级动画编程”学习:第三章等角投影(上)
什么是等角投影(isometric)? 原作者:菩提树下的杨过出处:http://yjmyzz.cnblogs.com 刚接触这个概念时,我也很茫然,百度+google了N天后,找到了一些文章: [转 ...
- FortiGate日常检查
1.1)CPU利用率:由于防火墙有芯片,正常的流量都走芯片转发,不走cpu,只有开了utm相关的应用层防护功能和DDOS之类的,才会走cpu,所以一般cpu都不会占用太多,甚至很多时间都是0%, 如果 ...
- 384. Shuffle an Array数组洗牌
[抄题]: Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. i ...
- C#跨窗体传值的几种方法分析(很详细)
创建一个Winform窗体应用程序项目,然后添加一个Form2窗体. 在Form1和Form2中各添加一个textBox和button: 单击Form1中的button1,弹出Form2,然后要做的就 ...
- css3回顾 checkbox
<div class="checkBox"> <input type="checkbox" id="check1"> ...
- [Selenium] 在Chrome的开发者工具中验证检查XPath/CSS selectors
Evaluate and validate XPath/CSS selectors in Chrome Developer Tools Method 1 : From Elements panel U ...
- 一句话shell【php】
1.mysql执行语句拿shell Create TABLE a (cmd text NOT NULL); Insert INTO a (cmd) VALUES('<?php @eval($_P ...
- poj2240
一个关于套利的题,就是判断是否有正环,我这里是用的SPFA,只要判断出来一种货币初始为1,最后变得大于1就代表是正环,要注意一下最后对vector的清空,当时从1开始清空,导致wa了两次,找了半天,尽 ...
- hibernate的Could not execute JDBC batch update错误原因及处理
http://blog.csdn.net/derpvailzhangfan/article/details/2332795\ 上述问题: 一设置关联 二包含关键字 三 映射文件设置 catalog=“ ...