GolangNote

Golang笔记

golang interface 概念理解

Permalink

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

golang 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"))
}

Related articles

Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

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

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