Go的功能和方法有什么区别? [英] Whats the difference of functions and methods in Go?

查看:119
本文介绍了Go的功能和方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图开始使用Go,文档非常好。我在文档中找不到的是函数和方法之间的区别。



据我现在了解:函数是全局的,这意味着我做不需要导入一个包来使用函数,它们总是在那里。方法绑定到包。这是正确的吗?

解决方案


据我现在了解:函数是全局 ,这意味着我不必导入包来使用函数,它们总是在那里。方法绑定到包。这是正确的吗?


不,那是不正确的。 内置软件包中的一些功能始终可用。其他所有内容都需要导入。



术语方法提出了面向对象编程。在OOP语言中(例如C ++),您可以定义一个类来封装属于一起的数据和函数。这些类中的函数称为方法,您需要该类的实例来调用这样的方法。

在Go中,术语基本相同,尽管Go不是古典意义上的OOP语言。在Go中,一个接收器的函数通常称为方法(可能仅仅是因为人们仍然习惯于OOP的术语)。

所以,例如: / p>

  func MyFunction(a,b int)int {
返回a + b
}
//用法:
// MyFunction(1,2)

但是

 类型MyInteger int 
func(a MyInteger)MyMethod(b int)int {
return a + b
}
//用法:
// var x MyInteger = 1
// x.MyMethod(2)


I am trying to get started with Go and the documentation is very good. What I did not find in the documentation is the difference between functions and methods.

As far as I understand at the moment: functions are "global", which means I do not have to import a package to use functions, they are always there. Methods are bound to packages. Is this correct?

解决方案

As far as I understand at the moment: functions are "global", which means I do not have to import a package to use functions, they are always there. Methods are bound to packages. Is this correct?

No, that's not correct. There are just a couple of functions from the builtin package which are always available. Everything else needs to be imported.

The term "method" came up with object-oriented programming. In an OOP language (like C++ for example) you can define a "class" which encapsulates data and functions which belong together. Those functions inside a class are called "methods" and you need an instance of that class to call such a method.

In Go, the terminology is basically the same, although Go isn't an OOP language in the classical meaning. In Go, a function which takes a receiver is usually called a method (probably just because people are still used to the terminology of OOP).

So, for example:

func MyFunction(a, b int) int {
  return a + b
}
// Usage:
// MyFunction(1, 2)

but

type MyInteger int
func (a MyInteger) MyMethod(b int) int {
  return a + b
}
// Usage:
// var x MyInteger = 1
// x.MyMethod(2)

这篇关于Go的功能和方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆