Golang变通实现class类

Go里没有class关键字,一切一切都是函数,这也是我非常喜欢的编程方式。

package main

import "fmt"

func main() {
  b := sum(5, 7)
  fmt.Println(b)
}

func sum(a int, b int) int {
  return a + b
}

如果你非得想使用类的方式来编程,可以这么干

package main

import "fmt"

type Utility struct {}

func (u *Utility) sum(a int, b int) int {
  return a + b
}

func main() {
  u := &Utility{}

  b := u.sum(5, 7)
  fmt.Println(b)
}

在函数前定义所属struct,那么这个函数就会属于这个struct的方法,如果多个struct共享一个function呢?可以这么干

package main

import "fmt"

type Person struct {
}

type Student struct {
  Person
}

type Teacher struct {
  Person
}

func (p *Person) say() string {
  return "Hello World!"
}

func main() {
  s := &Student{}

  t := &Teacher{}

  fmt.Println(s.say())
  fmt.Println(t.say())
}

Output

Hello World!
Hello World!
分享

TITLE: Golang变通实现class类

LINK: https://www.qttc.net/273-golang-class.html

NOTE: 原创内容,转载请注明出自琼台博客