[英]Can I have a function inside my struct? Converting from PHP class
I have some php code which I'm trying to migrate to Golang code.我有一些 php 代码,我正在尝试迁移到 Golang 代码。 This is it:
就是这个:
Code in PHP: PHP 中的代码:
class AuditProcessor {
public function __construct( BfsBlockChain $Bfs )
{
$this->bfs = $bfs;
}
I know this is a class, and there is a function inside of it.我知道这是一个 class,里面有一个 function。 My question is: in Golang, can I have a function inside my struct?
我的问题是:在 Golang 中,我的结构中可以有一个 function 吗? Or how can I replace the code, or format it?
或者我该如何替换代码或格式化它?
You can have fields of function type , and you can also have methods .可以有function 类型的字段,也可以有方法。 To fields you can assign any function values (with matching signature), methods are not changeable.
对于可以分配任何 function 值(具有匹配签名)的字段,方法是不可更改的。
For example:例如:
type Foo struct {
Bar func() // This is a regular field of function type
}
func (f Foo) Baz() { // This is a method of Foo
fmt.Println("I'm Baz()")
}
Testing it:测试它:
func main() {
f := Foo{
Bar: func() { fmt.Println("I'm Bar()") },
}
f.Bar()
f.Baz()
f.Bar = Bar2
f.Bar()
}
func Bar2() {
fmt.Println("I'm Bar2()")
}
Output (try it on the Go Playground ): Output(在Go Playground上尝试):
I'm Bar()
I'm Baz()
I'm Bar2()
See related: Functions as the struct fields or as struct methods参见相关: 作为结构字段或结构方法的函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.