Golang(5)Interface and Concurrence
2.6 Interface
Interface is a collection of methods.
Interface Type
Define the Interface
type Men interface {
SayHi()
Sing(lyrics string)
Guzzle(beerStein string)
}
type YoungChap interface {
SayHi()
Sing(song string)
BorrowMoney(amount float32)
}
type ElderlyGent interface {
SayHi()
Sing(song string)
SpendSalary(amount float32)
}
interface Value
Men interface variable can store the parameters who implement this interface, for example, Human, Student, Employee instances.
func main(){
mike := Student{Human{“Mike”, 25, “222-222-xxx”}, “MIT”, 0.00}
sam := Employee{Human{“Sam”, 36, “444-222-xxx”}, “Golang Inc.”, 1000}
var i Men //define a variable from Interface
i = mike // i can be a student
i.SayHi()
i = sam // i can be employee
//slice of Men, but different objects
x := make([]Men, 2)
x[0], x[1] = mike, sam
for _, value := range x{
value.SayHi()
}
}
Empty interface
var a interface{}
a can stores all the different types of instances.
var i int = 5
s:=“hello sillycat”
a = i
a = s
interface Function Parameters
for example, fmt.Println can accept all the parameters who implement string interface
type Stringer interface{
String() string
}
package main
import (
“fmt”
“strconv"
)
type Human struct {
name string
age int
phone string
}
func (h Human) String() string {
return “<“ + h.name + “ - “ + strconv.Itoa(h.age) + “ years - phone: “ + h.phone + “>"
}
func main() {
Bob := Human{“Bob”, 39, “000-7777-xxx”}
fmt.Println(“This Human is : “, Bob)
}
Type of Interface
We know that interface variable can hold all the instances who implement this interface, how will we know that which class is that instance?
Comma-ok
value, ok = element.(T) value is the value of the variable, ok is bool, lament is the interface variable, T is the type.
For example
list := make(List, 3)
list[0] = 1
list[1] = “Hello”
for index, element := range list {
if value, ok := element.(int); ok {
fmt.Printf(“list[%d] is an int and its value is %d\n”, index, value)
}
else if value, ok := element.(string); ok {
fmt.Printf(“list[%d] is a string and its value is %s\n”, index, value)
}
}
switch Test
The same example as follow>
for index, element := range list {
switch value := element.(type) {
case int:
fmt.Printf(“list[%d] is an int and its value is %d\n”, index, value)
case string:
fmt.Printf(“list[%d] is a string and its value is %s\n”, index, value)
default:
fmt.Println(“list[%] is of a different type”, index)
}
}
element.(type) this can only be used in switch statement.
Inner Interface
type ReadWriter interface {
Reader
Writer
}
Reflect
Laws of Reflection
http://blog.golang.org/laws-of-reflection
2.7 Concurrence
goroutine
go key word can start a go routine
package main
import (
"fmt"
"runtime"
)
func say(s string) {
for i := 0; i < 5; i++ {
runtime.Gosched()
fmt.Println(s)
}
}
func main() {
go say("world") //开一个新的Goroutines执行
say("hello") //当前Goroutines执行
}
Channels
ci : = make(chan int)
cs := make(cha string)
cf := make(cha interface{})
ch <- v //send v to channel ch
v := <- ch //receive data from ch, give the value to v
package main
import "fmt"
func sum(a []int, c chan int) {
total := 0
for _, v := range a {
total += v
}
c <- total // send total to c
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
sparkworker1:easygo carl$ go run src/com/sillycat/easygoapp/main.go 17 -5 12
Buffered Channel
ch := make(chan type, value)
value == 0 // no buffer, block
value > 0 // buffer, no block
package main
import "fmt"
func main() {
c := make(chan int, 5) //修改2为1就报错,修改2为3可以正常运行
c <- 1
c <- 2
fmt.Println(<-c)
fmt.Println(<-c)
}
Range and Close
for i := range c
close(c)
Select
…snip…
Expiration time
…snip…
Runtime Goruntine
Goexit, Gosched, NumCPU, NumGoroutine, GOMAXPROCS
References:
https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/02.6.md
golang 1~4
http://sillycat.iteye.com/admin/blogs/2037798
http://sillycat.iteye.com/admin/blogs/2047158
http://sillycat.iteye.com/admin/blogs/2052936
http://sillycat.iteye.com/admin/blogs/2052937
revel
http://revel.github.io/tutorial/index.html
http://www.cnblogs.com/ztiandan/archive/2013/01/17/2864498.html
martini
http://0value.com/build-a-restful-API-with-Martini
https://github.com/go-martini/martini
https://github.com/PuerkitoBio/martini-api-example
goweb
http://www.giantflyingsaucer.com/blog/?p=4673
https://github.com/stretchr/goweb
http://joshua.themarshians.com/hardcore-google-communicating-go.html
json-go
https://gobyexample.com/json
http://blog.golang.org/json-and-go
- 浏览: 2539954 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 467NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 328Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 428Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 376Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 464NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 413Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 330Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 242GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 443GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 320GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 306Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 310Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 285Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 302Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 276NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 254Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 564NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 255Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 356Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 363Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
在Golang中,接口(Interface)是一种类型定义,它定义了一组方法签名。任何具有相同方法集的类型都隐式地实现了该接口。接口提供了一种抽象机制,使得代码能够处理多种不同类型的对象,而无需知道它们的具体类型。...
《Learn Data Structures and Algorithms with Golang》是一本专注于使用Golang语言学习数据结构和算法的电子书,旨在帮助读者深入理解这两个编程领域的核心概念。Golang,也被称为Go语言,是由Google开发的一种静态...
在Golang中,接口(interface)是语言设计的关键特性,它提供了一种抽象类型的方式,允许程序员定义一组方法集合,并让任何实现了这些方法的类型都能符合接口的要求。接口的使用使得代码更加灵活,有助于实现面向切...
golang type assertion and unsafe.Pointer 性能对比 最近项目中有这样一个需求背景:有一个存储实体用来做各种指标的counter。这个counter的实现需要能够在以后被别的实现替换。结构自然是这样: type XXXObj ...
本文主要给大家介绍了关于golang中struct和interface的相关内容,是属于golang的基本知识,下面话不多说了,来一起看看详细的介绍吧。 struct struct 用来自定义复杂数据结构,可以包含多个字段(属性),可以嵌套...
2. **公钥和私钥(Public Key and Private Key)**:在RSA加密算法中,公钥用于加密,私钥用于解密。在PKCS#1中,私钥通常以PEM编码存储,而公钥可以是PEM或DER编码。 3. **PKCS#1**:Public-Key Cryptography ...
weixin-golang-sdk 微信golang工具包
Go语言,又称Golang,是由Google开发的一种静态类型、编译型、并发型且具有垃圾回收功能的编程语言。它设计的目标是提高开发者的生产效率,同时保持系统级编程的性能。Go语言的设计受到了C、 Pascal、 Miranda和...
golang安装包下载
5. **错误处理**:Golang有独到的错误处理机制,比如使用panic、defer和recover来处理程序中可能发生的异常。掌握这些机制有助于编写更健壮的程序。 6. **文件与数据操作**:Golang提供了强大的包用于文件的读写...
Golang 1.18.10 Windows安装包。Golang 1.18.10 Windows安装包。Golang 1.18.10 Windows安装包。Golang 1.18.10 Windows安装包。Golang 1.18.10 Windows安装包。Golang 1.18.10 Windows安装包。Golang 1.18.10 ...
golang_http_client
5. **golang.org/x/image**:图像处理和图形库,支持多种图像格式的读写,以及图像操作,如缩放、旋转和滤波。 6. **golang.org/x/tools**:这个包是一组开发工具,包括代码分析、格式化、性能分析和Go语言服务器...
5. **错误处理**:Go语言使用`error`类型进行错误处理,文档会详细解释如何创建和处理错误。 6. **反射与类型断言**:讨论如何在运行时检查和使用变量的类型,以及如何进行类型断言。 7. **标准库**:详述Go语言的...
在编程领域,Go语言(Golang)以其高效、简洁和并发特性受到了许多开发者的青睐。在Windows平台上,尽管Go语言最初的设计目标并非图形用户界面(GUI)开发,但随着技术的发展,已经出现了一些优秀的框架使得Go语言也...
golang 实现海康相机抓拍,目前只支持球机。需要在代码中设置用户名和密码。 如何调试?用vscode打开,安装golang插件,即可直接调试运行。 编译与运行:运行go build命令,将HKnet.exe拷贝到build\Windows下,运行...
1、适合新手使用,详细的代码和举例 2、hmacMd5的方法网上资料少
Golang Windows 1.19.1版本安装包
Golang,作为一种现代且高效的编程语言,因其强大的系统级编程能力和并发特性而受到广泛欢迎。在本文中,我们将深入探讨如何利用Golang实现这个功能,并了解相关的核心知识点。 首先,我们需要了解的是Golang的图形...
golang提取office文件内容,可以支持正常office文件内容格式,可以很好的提取标点以及内在格式内容