golang struct interface 方法

发布时间 2023-07-08 13:44:00作者: 秋来叶黄

有一个结构体

type mystruct struct {
  a int
}

如果想为这个结构体增加一个方法,就类似于C++或者Java的类一样,有成员变量,也有成员函数,怎么实现呢?由于go没有类的概念,所以提供了一种方案。

func (ms mystruct) test() int {
  return ms.a
}

就是按照定义函数的方式,只不过在前面增加对应结构体或者接口的参数。这里就是定义了一个函数test(),返回值是int,对应的是mystruct结构体(mystruct中的方法),由于我们调用类的方法是都是实例化一个类,然后用类的实例进行调用。比如:

Class A {
    void test() {
    }
};

A a;
a.test();

所以go中方法前面的参数(ms mystruct)就表示在调用的时候,把当前的实例传递进来。一般我们会写成指针的形式,避免传递了形参,数据没有改变:

func (ms *mystruct) test() int {
  return ms.a
}

具体使用如下

func main() {
  var ms1 mystruct
  ms1.a = 10
  fmt.Println(ms1.test())
}

ms1.test()就是调用func (ms *mystruct) test() int函数,把自己传递进去,func (ms *mystruct) test() int就是传递ms1的指针,func (ms mystruct) test() int就是传递ms1的形参。

不过go的这个特性有个问题,不能很明显的知道结构体或者接口有哪些方法。当然也有一个好处就是灵活。