Golang嵌套函数内部的类 [英] Golang nested class inside function

查看:605
本文介绍了Golang嵌套函数内部的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go支持嵌套的struct inside函数,但除lambda之外没有嵌套函数,这是否意味着无法在函数内定义嵌套类?

 < code $ func f(){
//嵌套结构Cls在f
类型中Cls struct {
...
}
//尝试边界foo到Cls但没有
func(c * Cls)foo(){
...
}
}

因此,感觉有点奇怪,因为类在函数内部变弱了。

任何提示?

解决方案

实际上,如果您想用或声明功能而不用一个接收器:在Go中嵌套函数是不允许的。



虽然你可以使用

  func f(){
foo:= func(s string){
fmt.Println(s)
}

foo(Hello World!)
}

创建了一个变量 foo ,它有一个函数类型,并且在另一个函数 f 内部被扩展。按照预期,调用外部函数 f 输出:Hello World!



请试试去游乐场


Go supports nested struct inside function but no nested function except lambda, does it mean there is no way to define a nested class inside function?

func f() {
    // nested struct Cls inside f
    type Cls struct {
    ...
    }
    // try bounding foo to Cls but fail
    func (c *Cls) foo() {
    ...
    }
}

Thus it feels a bit strange that class is weaken inside function.

Any hints?

解决方案

Actually it doesn't matter if you want to declare the function with or without a receiver: nesting functions in Go are not allowed.

Although you can use Function literals to achieve something like this:

func f() {
    foo := func(s string) {
        fmt.Println(s)
    }

    foo("Hello World!")
}

Here we created a variable foo which has a function type and it is delcared inside another function f. Calling the "outer" function f outputs: "Hello World!" as expected.

Try it on Go Playground.

这篇关于Golang嵌套函数内部的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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