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

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

问题描述

Go 支持在函数内部嵌套结构体,但除了 lambda 不支持嵌套函数,是否意味着无法在函数内部定义嵌套类?

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.

有什么提示吗?

推荐答案

实际上,声明函数with 还是without 接收器并不重要:不允许在 Go 中使用嵌套函数.

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!")
}

这里我们创建了一个变量foo,它有一个函数类型,它被定义在另一个函数f中.调用外部"函数 f 输出:"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.

Go Playground 上试试.

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

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