Go中的函数和方法有什么区别? [英] Whats the difference of functions and methods in Go?
问题描述
我正在尝试开始使用 Go,文档 非常好.我在文档中没有找到函数和方法的区别.
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?
不,这不正确.builtin 包中只有几个函数始终可用.其他一切都需要导入.
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.
术语方法"是在面向对象编程中出现的.在 OOP 语言(例如 C++)中,您可以定义一个类",它封装了属于一起的数据和函数.类中的那些函数称为方法",您需要该类的实例来调用这样的方法.
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.
在 Go 中,术语基本相同,尽管 Go 不是经典意义上的 OOP 语言.在 Go 中,接受接收者的函数通常称为方法(可能只是因为人们仍然习惯于 OOP 的术语).
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).
例如:
func MyFunction(a, b int) int {
return a + b
}
// Usage:
// MyFunction(1, 2)
但是
type MyInteger int
func (a MyInteger) MyMethod(b int) int {
return a + b
}
// Usage:
// var x MyInteger = 1
// x.MyMethod(2)
这篇关于Go中的函数和方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!