GolangNote

Golang笔记

golang interface 概念理解

Permalink

比如有一些不同的数据结构structs (Models),都有相同的函数,如(Update, Delete, Show),这时候应该引入interface。

如下面一个例子:

Go: interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import "fmt"

type human struct {
  something string
}
type animal struct {
  whatever string
}

func (a *animal) Speak() string {
  return a.whatever
}
func (h *human) Speak() string {
  return h.something
}

type living interface {
  Speak() string
}

func AnyMethod(l living) {
  fmt.Println(l.Speak())
}

func main() {
  fmt.Println("Hello, playground")
  john := human{"I am john"}
  tom := animal{"Bow Bow"}

  AnyMethod(&john)
  AnyMethod(&tom)

}

运行输出:

Bash: output
1
2
3
Hello, playground
I am john
Bow Bow

再看一个例子加强印象:

Go: interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main

import "fmt"

type A struct {
  Value string
}

func (a *A) Read() string {
  return a.Value
}

func (a *A) Write(s string) {
  a.Value = s
}

type B struct {
  Value string
}

func (b *B) Read() string {
  return b.Value
}

func (b *B) Write(s string) {
  b.Value = s
}

type ReadWriter interface {
  Read() string
  Write(s string)
}

func WriteRead(rw ReadWriter, s string) string {
  rw.Write(s)
  return rw.Read()
}

func main() {
  a := A{}
  b := B{}
  fmt.Println(WriteRead(&a, "a: write"))
  fmt.Println(WriteRead(&b, "b: write"))
}

本文网址: https://golangnote.com/topic/76.html 转摘请注明来源

Related articles

Golang 泛型性能初识

编程时,我们通常需要编写“泛型”函数,其中确切的数据类型并不重要。例如,您可能想编写一个简单的函数来对数字进行求和。Go 直到最近才有这个概念,但最近才添加了它(从1.18版开始)。...

Golang http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

Golang phantomjs 动态代理实现

phantomjs 是个很优秀的软件,虽然现在被chrome headless 抢了风头,但在某些特定场合,使用phantomjs 还是很方便,这里是介绍使用Go 实现动态代理。...

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Golang telegram 机器人小试

telegram 的机器人接口很开放,使用简单,100%开放无限制,相对微信服务号、公众号好很多。用来做一些小应用也很方便。下面是使用golang sdk 开发telegram 机器人的经验。...

Golang WebAssembly 了解一下

Go 1.11 起开始支持 WebAssembly ,也就是说以后可以使用任何语言作为“前端语言”来进行 Web 开发。...

Write a Comment to "golang interface 概念理解"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms